如何在grep中转义管道字符?

时间:2014-05-21 00:47:32

标签: shell grep escaping pipe

我有这种格式的文件:

coupait ||| eastern ||| 0.045454545454545456 2.718 ||| 0-0 ||| 
instaurer ||| characteristic ||| 5.797101449275362E-4 2.718 ||| 0-0 |||
tiendrait ||| fails ||| 0.005 2.718 ||| 0-0 |||

我希望搜索一对保存在两个变量中并由|||分隔的单词。 我尝试了许多替代方案,如:

grep "$word1 ||| $word2 |||" $file

我试图逃避这样的管道字符:

grep '$word1 \|\|\| $word2 \|\|\|' $file

如何匹配文件中的管道?

1 个答案:

答案 0 :(得分:4)

使用grep -F - 变量将由shell解释并替换为它们各自的值,然后引用的字符串(包括管道)将被解释为固定字符串。例如:

$ cat file.txt
coupait ||| eastern ||| 0.045454545454545456 2.718 ||| 0-0 ||| 
instaurer ||| characteristic ||| 5.797101449275362E-4 2.718 ||| 0-0 |||
tiendrait ||| fails ||| 0.005 2.718 ||| 0-0 |||
$ word1=coupait
$ word2=eastern
$ grep -F "$word1 ||| $word2 |||" file.txt
coupait ||| eastern ||| 0.045454545454545456 2.718 ||| 0-0 |||