Kyriakos
Kyriakos

Reputation: 757

How to redirect grep to a while loop

Hi I have the following bash script code

group2=0
    while read -r line
    do
      popAll=$line | cut -d "{" -f2 | cut -d "}" -f1 | tr -cd "," | wc -c
        if [[ $popAll = 0 ]]; then
          group2 = $((group2+2)); 
        else
          group2 = $((group2+popAll+1));
        fi
    done << (grep -w "token" "$file")

and I get the following error:

./parsingTrace: line 153: syntax error near unexpected token `('
./parsingTrace: line 153: `done << (grep -w "pop" "$file")'

I do not want to pipe grep to the while, because I want variable inside the loop to be visible outside

Upvotes: 4

Views: 4322

Answers (1)

fedorqui
fedorqui

Reputation: 289555

The problem is in this line:

done << (grep -w "token" "$file")
#    ^^

You need to say < and then <(). The first one is to indicate the input for the while loop and the second one for the process substitution:

done < <(grep -w "token" "$file")
#    ^ ^

Note however that there are many others things you want to check. See the comments for a discussion and paste the code in ShellCheck for more details. Also, by indicating some sample input and desired output I am sure we can find a better way to do this.

Upvotes: 8

Related Questions