如何将grep重定向到while循环

时间:2015-08-07 13:27:00

标签: bash while-loop grep

您好我有以下bash脚本代码

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")

我收到以下错误:

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

我不想把grep传递给while,因为我希望循环内的变量在外面可见

1 个答案:

答案 0 :(得分:6)

问题出在这一行:

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

您需要说<然后<()。第一个是指示while循环的输入,第二个指示process substitution的输入:

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

但请注意,您还需要检查其他许多内容。有关详细信息,请参阅讨论的评论并将代码粘贴到ShellCheck中。此外,通过指示一些样本输入和所需输出,我相信我们可以找到更好的方法来做到这一点。