Linux 在shell中将变量传递给grep

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18641909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:45:05  来源:igfitidea点击:

Passing variable to grep in shell

linuxbashvariablesgrep

提问by user2517676

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?

我编写了以下 shell 来计算以“A valA B valB”模式开头的行数。但是,我认为我没有正确传递变量。任何帮助解决这个问题?

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

采纳答案by konsolebox

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

使用正确的bash 引用。变量不在 内部展开''。请参阅链接以供参考。

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 

回答by anubhava

  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 -cfor counting the matches
  1. 您需要正确的 shell 引用(对 shell 的变量扩展使用双引号)
  2. 你不需要wc -l,你可以直接grep -c用于计算比赛

You can use:

您可以使用:

grep -c "^ A : $i B : $j" file