访问手机版  

Linux常用命令|Linux培训学习|考试认证|工资待遇与招聘,认准超级网工!

招聘|合作 登陆|注册

网络工程师培训

当前位置:网络工程师 > 技术课程 > linux > 热点关注 > linux常用命令

linux grep命令详解

时间:2019-06-30

linux命令大全 ssh_红帽linux命令大全_linux命令大全

Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹 配的行打印出来。grep全称是Global Regular Expression Printlinux命令大全,表示全局正则表达式版本,它的使用权限是所有用户。

grep (global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。

Unix的grep家族包括grep、egrep和fgrep。egrep和fgrep的命令只跟grep有很小不同。egrep是grep的扩展,支持更多的re元字符, fgrep就是fixed grep或fast grep,它们把所有的字母都看作单词,也就是说,正则表达式中的元字符表示回其自身的字面意义,不再特殊。linux使用GNU版本的grep。它功能更强,可以通过-G、-E、-F命令行选项来使用egrep和fgrep的功能。

grep能够快速的对文件进行搜索linux命令大全,命令和参数都比较好理解:

linux命令大全 ssh_红帽linux命令大全_linux命令大全

grep [-acinv] [--color=auto] '搜寻字符串' filename

选项与参数:

为了方便使用这个命令,先建立一个用来测试的文件,文件的内容如下:

The Wrong Man
1956 film by Alfred Hitchcock
The Wrong Man is typical of most of his films. In The Wrong Man he appears only in silhouette, just before the credits at the beginning of the film, where he tells a darkened studio that the story is true.

linux命令大全_linux命令大全 ssh_红帽linux命令大全

搜索含有Man的句子:

root@ubuntu:~# grep -n Man  grep_text.txt 
1:The Wrong Man
3:The Wrong Man is typical of most of his films. In The Wrong Man he appears only in silhouette, just before the credits at the beginning of the film, where he tells a darkened studio that the story is true.

其中 -n 为显示出有搜索到的句子在第几行。其他的参数同样可以使用如:

root@ubuntu:~# grep -n -i -v Man  grep_text.txt 
2:1956 film by Alfred Hitchcock 
4:

linux命令大全_linux命令大全 ssh_红帽linux命令大全

可以对照上面对参数的说明,-n -i -v ,其中-v是显示搜索不到的行数。

在linux的命令中,有些命令显示了大量的内容,不容易查看可以通过grep过滤,得到想要的结果,如命令ps ax 显示了大量的,使用grep过滤相关进程。

    root@ubuntu:~# ps ax | grep -n python
149:  5574 pts/0    Tl     0:00 /usr/bin/python /usr/local/bin/scrapy crawl iiSpider
150:  5589 pts/0    T      0:00 /usr/bin/python /usr/local/bin/scrapy crawl ccSpider
151:  5714 pts/0    T      0:00 /usr/bin/python /usr/local/bin/scrapy crawl ddSpider

python也是支持正则表达式的,至于正则表达式,跟其他的语言如java,c没什么差别,这里说说如何使用正则表达式来进行匹配:。有关正则表达式的语法还有最后一个元素,那就是正则表达式的属性,它说明的是高级模式匹配的规则.和其它正则表达式语法不同,属性是在 / 符号之外说明的.即它。@pattern 验证 string 对象是否符合正则表达式的规则,被注释的元素符合制定的正则表达式,regexp:正则表达式 flags: 指定 pattern.flag 的数组,表示正则表达式的相关选项。

linux命令大全_红帽linux命令大全_linux命令大全 ssh

RE(正则表达式)

\ 忽略正则表达式中特殊字符的原有含义

查看带数字的行:

root@ubuntu:~# grep -n [0-9]  grep_text.txt 
2:1956 film by Alfred Hitchcock 

查看The开头的行