Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

regex - Difference between egrep and grep

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...