Difference between egrep and grep

The egrep command is a shortcut for the grep binary, but with one exception: when grep is invoked as egrep, the grep binary activates its internal logic to run as if it were called as grep -E.

The difference is that -E option enables usage of extended regexp patterns. This allows use of meta-symbols such as +, ? or |. These aren't ordinary characters like we may use in words or filenames but are control commands for the grep binary itself. Thus, with egrep, the character | means logical OR.

So, for example, you want to list files in a directory and see only those which contain "mp4" or "avi" as filename extensions. With egrep you will do:

ls | egrep "mp4|avi"

In this example | acts like an OR command. It will grab to output from ls all names which contain either "mp4" or "avi" strings. If you run it with a plain grep command you will get nothing, because grep doesn't know such thing as | command. Instead, grep will search for "mp4|avi" as a whole text string (with pipe symbol). E.g. if you have a file named |mp4|avi|cool-guy.q2.stats in your dir, you will get it with plain grep searching with pipes.

So, that is why you should escape | in your egrep command to achieve the same effect as in grep. Escaping will screen off the special meaning of | command for grep binary.


Extracted from grep explained and man pages.

grep provides matcher selection options.
-E Interpret pattern as an Extended Regular Expression (ERE)
-G Interpret pattern as a Basic Regular Expression (BRE). This is the default when no option is specified.

The variant program egrep is the same as grep -E. The variant is deprecated, but is provided for backward compatibility.

Therefore,
grep implies grep -G
egrep implies grep -E

There are two interpretations of the syntax in regex patterns. The difference is in the behavior of a few special characters, ?, +, (), {}, and |.

  • BRE (Basic Regular Expression) – these characters do not have special meaning unless prefixed with a backslash \.
  • ERE (Extended Regular Expression) – these characters are special, unless prefixed with a backslash \.

Since ^ has the same interpretation by grep(BRE) and egrep(ERE) it works the same in both.
However, | is one of those characters which are interpreted differently by grep(BRE) and egrep(ERE) so it requires to be escaped with a \ depending on the regex intent.


The difference between grep and egrep is:

grep

  • It uses Basic Regular Expression which means if you use grep 'a|b' it will not not use this "|" as OR operator without using this "\" prefix.
  • It searches for PATTERN in each FILE.

egrep

  • It uses Extended Regular Expression and in this you can use commands like this egrep 'a|b'
  • It treats meta-character as it is and does not substitute them as strings like grep.