Differences Between Grep and Grep -f

grepregular expression

I have a file with the following 3 lines:

file.txt

aaa|
bbb|
ccc|

and another file with one line:

regex.txt

^aaa\|

$grep ^aaa\| file.txt yields:

aaa|

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

aaa|
bbb|
ccc|

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

Best Answer

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.

Related Question