0

I'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.

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

instead of

for f in $f1 $f2 $f3

use

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

and rename your $f1 in the inner loop!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.