I have a question about grep
and egrep
in unix
.
As I am recently studying the shell commands
in unix
, I want to know what are the differences between grep and egrep.
I find we can use grep and egrep with regular expression. However, I found something different between these two commands:
For ^
, grep and egrep have the same meaning which is finding the lines contain the given stuffs at the very beginning.
However, for |
, grep, without back slash in front of |
, means character of |
, and if I put a back slash in front of it, it turns on it special meaning of finding the line contains either the stuff in front of it and behind it. BUT, for egrep, it is the opposite. |
has the latter meanings of grep and \|
has the former meaning of grep when uses it.
Could somebody else kindly explain why?
Example: Note: The egrep command used mainly due to the fact that it is faster than the grep command. The egrep command treats the meta-characters as they are and do not require to be escaped as is the case with grep.
egrep is an acronym for "Extended Global Regular Expressions Print". It is a program which scans a specified file line by line, returning lines that contain a pattern matching a given regular expression.
On Unix-like operating systems, the egrep command searches for a text pattern, using extended regular expressions to perform the match. Running egrep is equivalent to running grep with the -E option.
Direct invocation as either egrep or fgrep is deprecated, but is provided to allow historical applications that rely on them to run unmodified.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With