12

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
1
  • 2
    Are the double-quotes part of the text to be matched, or is that an attempt at triggering variable expansion? Commented Sep 5, 2013 at 17:05

2 Answers 2

20

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

Comments

9
  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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.