Dorra Dorra - 16 days ago 14
Bash Question

how to escape the pipe character in grep?

I have a file in this format:

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


and I would like to search for a pair of words that are saved in two variables and which are seperated by |||.
I tried many alternatives in vain like :

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


I tried escaping the pipe characters like this:

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


How can I match the pipe in the file?

Answer

Use grep -F - the variables will be interpreted by the shell and replaced with their respective values, then the quoted string (including the pipes) will be interpreted as a fixed string. Example:

$ 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 ||| 
Comments