开发者

problem with redirecting output

开发者 https://www.devze.com 2022-12-13 01:19 出处:网络
I开发者_如何学C\'m writing a script that selects rows from files in a directory which contain patterns $f1, $f2 and $f3 and storing the lines that contain the pattern in a file I want to call as $file

I开发者_如何学C'm writing a script that selects rows from files in a directory which contain patterns $f1, $f2 and $f3 and storing the lines that contain the pattern in a file I want to call as $file_$pattern.xls, for example file1_2.54 Ghz.xls.

#!/bin/bash

#my_script.sh to summarize p-state values

f1="2.54 Ghz"
f2="1.60 Ghz"
f3="800 Mhz"

for f in $f1 $f2 $f3
do
    for file in *.txt  
    do
        grep $f1 $file > ${file}_${f1}.xls
    done
done

Kindly help me with the script.


Two things...

  1. Inside the for loop, use $f instead of $f1.
  2. Put quote marks around $f. The spaces cause bash to break apart the string.

Something like this might work:

#!/bin/bash
#my_script.sh to summarize p-state values

f1="2.54 Ghz"
f2="1.60 Ghz"
f3="800 Mhz"

for f in "$f1" "$f2" "$f3"
do
    for file in *.txt 
    do
    grep "$f" "$file" > "${file}_${f}.xls"
    done
done


You can do everything in the shell, no need grep or other external tools

#!/bin/bash

f1="2.54 Ghz"
f2="1.60 Ghz"
f3="800 Mhz"

for file in *.txt
do
    while read -r line
    do
        case "$line" in
            *"$f1"* ) 
                    echo "$line" >> "${file%txt}_${f1}.xls";;
            *"$f2"* ) 
                    echo "$line" >> "${file%txt}_${f2}.xls";;
            *"$f3"* ) 
                    echo "$line" >> "${file%txt}_${f3}.xls";;
        esac
    done < "$file"
done


instead of

for f in $f1 $f2 $f3

use

for f in {$f1,$f2,$f3}

and rename your $f1 in the inner loop!

0

精彩评论

暂无评论...
验证码 换一张
取 消