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

标签 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

如何匹配文件中的管道?

最佳答案

使用 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 ||| 

关于shell - 如何在grep中转义管道字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23772231/

相关文章:

regex - 使用 grep 和 awk 在两个模式之间获取文本

c# - 如何转义 PowerShell 提供程序返回的路径名

python - 如何将这个json字符串转换为dict?

linux - 将字符串或数组中的代码插入到whiptail中

Bash 脚本 : How to ensure script exits on any error in function called with an "or" (||) condition?

linux - 如何使用类似于 SQL JOIN 的 awk/sed/grep/bash 加入文件

linux - 比较两个文件中的列并打印不匹配

powershell - 试图找到 IndexOf 引号字符

shell - 在 awk 中按特定顺序打印文件

amazon-web-services - 做cloudformation打包时如何在s3中动态创建文件夹