I have a file with the following 3 lines:



and another file with one line:



$grep ^aaa\| file.txt yields:


$grep -f regex.txt file.txt yields:


Why are the results different for grep -f and grep?

$grep -V
grep (GNU grep) 3.1

$lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.1 LTS
Release:    18.04
Codename:   bionic

2 Answers 2


You're using grep with basic regular expressions. grep ^aaa\| file.txt is the same as typing grep "^aaa|" file.txt. While reading the file grep -f regex.txt file.txt is the same as grep "^aaa\|" file.txt., the escaped | means match ^aaa or "" which matches anything.

  • 2
    In particular, on the command line the shell processes and removes the backslash (or the double-quotes you propose). While if the pattern is in a file, there is no shell involved, so greps regex engine sees the backslash. It's probably easiest to single-quote any such patterns on the shell command line, to ensure minimal processing by the shell. Also, it should be noted that \| for alternation in BRE is a GNU thing, and not standard.
    – ilkkachu
    Jul 23, 2019 at 6:23

When using regexp in file, you do not need the \ (escape). When in file it is treated as the \ char. In command it is treated as escape and ignored (due to the lack of quoting of the expression).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.