Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable to grep in shell [duplicate]

I have written the following shell to count the number of lines starting with the pattern of " A valA B valB". However, I think that I have not passed variables properly. Any help to fix that?

for i in {0..16};
do
    for j in {0..16}; 
    do
        echo A $i B $j 
        grep '^ A : "$i" B : "$j"' file | wc -l
    done
done
like image 509
user2517676 Avatar asked Sep 05 '13 16:09

user2517676


People also ask

Can we pass variable in grep command?

You can use the grep command or egerp command for any given input files, selecting lines that match one or more patterns. By default the output shown on screen. But, you can store output to variable in your shell scripts.

Can we use grep in shell script?

To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'. By default, grep searches for a pattern in a case-sensitive way.


2 Answers

Use proper bash quoting. Variables are not expanded inside ''. See the link for reference.

grep "^ A : $i B : $j" file | wc -l 

Also perhaps you mean this, but just try either.

grep "^ A : \"$i\" B : \"$j\"" file | wc -l 
like image 138
konsolebox Avatar answered Oct 14 '22 06:10

konsolebox


  1. You need right shell quoting (use double quotes for shell's variable expansion)
  2. You don't need wc -l, you can directly use grep -c for counting the matches

You can use:

grep -c "^ A : $i B : $j" file
like image 24
anubhava Avatar answered Oct 14 '22 07:10

anubhava