问题描述
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?
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.
这篇关于egrep 和 grep 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!