1.grep命令
1.Global search regular expression and print out the line(全面搜索研究正则表达示并显示出来)
2.grep 命令是一种强大的文本搜索工具,根据用户指定的“模式”对目标文本进行匹配检查,打印匹配到的行
3.由正则表达示或者字符及基本文本字符所编写的过滤条件
4.grep 的格式
grep 匹配条件 处理文件
例如:
grep root passwd
grep ^root passwd
grep root$ passwd
grep -i root passwd
grep -E “root|ROOT” passwd
5.grep中的正则表达示
^westos
westos$
‘w…s’
'w…
'…s
6.grep正则表达示与扩展正则表达示
正规的grep不支持扩展的正则表达式,竖线是用于表示“或”的扩展正则表达式元字符,正规的grep无法识别,加上反斜杠,这个字就被翻译成扩展正则表达式,就像egrep和grep -E一样
-1-实验:
前提(复制/etc/passwd文件并进行修改):
[root@localhost mnt]# cp /etc/passwd .
[root@localhost mnt]# vim passwd
[root@localhost mnt]# cat passwd
<1>##过滤passwd文件中的“root”
[root@localhost mnt]# grep root passwd
<2>##过滤passed文件中不论大小写的“root”
[root@localhost mnt]# grep -i root passwd
<3>##过滤passwd文件中root前没有内容的文本
[root@localhost mnt]# grep -i "\<root" passwd
<4>##过滤passwd文件”root“前后都没有内容的文本
[root@localhost mnt]# grep -i "\<root\>" passwd
<5>##过滤passwd文件中“root”后没有内容的文本
[root@localhost mnt]# grep -i "root\>" passwd
<6>##过滤passwd文件中以“root”开头且“root”后没有内容的文件
[root@localhost mnt]# grep -i "^root\>" passwd
<7>##过滤passwd文件中以“root”结尾且“root”前没有内容的文件
[root@localhost mnt]# grep -i "\<root$" passwd
<8>##过滤passwd文件中以“root”开头或以“root”为结尾的文本
[root@localhost mnt]# egrep -i "^root\>|\<root$" passwd
<9>##过滤passwd文件中以“root”开头或以“root”为结尾的文本
[root@localhost mnt]# grep -iE "^root\>|\<root$" passwd
<10>##过滤passwd文件中”root”在中间的文本
[root@localhost mnt]# grep -iE "^root\>|\<root$" passwd -v | grep "root"
注意:
由结果可知test:roottest:root并没有被过滤出来,原因是因为符合条件的roottest后还有一个root,前者符合条件,后者不符合条件,所以只要有不符合条件的内容,直接会被忽略
<11>##过滤passwd文件中”root”在中间并且前后没有内容的文本
[root@localhost mnt]# grep -iE “^root>|<root$” passwd -v | grep “<root>”
<12>##显示出passwd文件中的需要的几个字符
[root@localhost mnt]# grep r..t passwd ##过滤passwd文件中以r开头以t结尾的四个字符的内容
[root@localhost mnt]# grep r.... passwd ##过滤passwd文件中以r开头共5个字符的内容
[root@localhost mnt]# grep ....t passwd ##过滤passwd文件中以t结尾共5个字符的内容