grep的正规表达式元字符
^ 行首定位符
$ 行尾定位符
. 匹配任意一个字符
* 匹配0个或多个前导字符
[] 匹配指定范围内的其中一个字符
[^] 匹配不要范围内的字符
\< 词首定位符
/〉 词尾定位符
x\{m\} 重复x字符m次
x\{m,\} 重复x字符最少m次
x\{m,n\} 重复x字符m到n次
文件内容:
[root@tong1 opt]# ll passwd
-rw-r--r--. 1 root root 1087 Mar 19 17:39 passwd
[root@tong1 opt]# cat passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
[root@tong1 opt]#
1.grep命令格式
grep [选项] 字符模式 [文件名1,文件名2.........]
-c:只输出匹配行的计数。
-I:不区分大 小写(只适用于单字符)。
-h:查询多文件时不显示文件名。
-l:查询多文件时只输出包含匹配字符的文件名。
-n:显示匹配行及 行号。
-s:不显示不存在或无匹配文本的错误信息。
-v:显示不包含匹配文本的所有行。
2.查找r开头的行
[root@tong1 opt]# grep '^r' passwd
3.查找以c结尾的行
[root@tong1 opt]# grep 'c$' passwd
4.查找以h开头,t结尾,中间只有两个字符的行
[root@tong1 opt]# grep '\<h..t\>' passwd
5.查找文件内容只要有h或q的字符
[root@tong1 opt]# grep '[hq]' passwd
6.查找每行有a到o字符出现7次的
[root@tong1 opt]# grep '[a-o]\{7\}' passwd
7.在一些文件中查找相同的内容
[root@tong1 opt]# grep root passwd*
passwd:root:x:0:0:root:/root:/bin/bash
passwd:operator:x:11:0:operator:/root:/sbin/nologin
passwd1:root:x:0:0:root:/root:/bin/bash
passwd1:operator:x:11:0:operator:/root:/sbin/nologin
8.显示grep结果的行号
[root@tong1 opt]# grep root -n passwd
1:root:x:0:0:root:/root:/bin/bash
11:operator:x:11:0:operator:/root:/sbin/nologin
9.显示包含字符的文件名
[root@tong1 opt]# grep root -l passwd
passwd
10.显示文件中的字符
[root@tong1 opt]# grep root -c passwd
2
11.查找内容是单词
[root@tong1 opt]# grep -w halt passwd
12.反向过滤
[root@tong1 opt]# grep -v bash passwd | grep -v nologin passwd
13.用-E解释通配符
[root@tong1 opt]# grep -v -E 'bash|nologin' passwd
本文转自 z597011036 51CTO博客,原文链接:http://blog.51cto.com/tongcheng/1622319,如需转载请自行联系原作者