egrep 和 grep 的区别 [英] Difference between egrep and grep

查看:14
本文介绍了egrep 和 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?

解决方案

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 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆