一.grep文本过滤命令
1.grep
全面搜索研究正则表达式并显示出来
grep命令是一种强大的文本搜索工具,根据用户指定的“模式”对目标文本进行匹配检查,打印到匹配的行。 由正则表达式或者字符及基本文本字符所编写的过滤条件 |
2.grep的格式
grep 匹配条件 处理文件
3.grep中字符的匹配位置设定
^关键字 | 以“关键字“开头 |
---|---|
关键字$ | 以关键字结尾 |
<关键字 | 关键字前没有字符 |
关键字> | 关键字后面没有字符 |
<关键字> | 关键字前后均没有字符 |
[root@shell mnt]# cp /etc/passwd .
[root@shell mnt]# ls
passwd
[root@shell mnt]# vim passwd
[root@shell mnt]# grep root passwd
[root@shell mnt]# grep -i root passwd ##过滤root其中包含大写
[root@shell mnt]# grep -i "\<root" passwd ##过滤root其中包含大写,并且以root开头
[root@shell mnt]# grep -i "\<root\>" passwd #root前后都不含有附加字符
[root@shell mnt]# grep -i "^\<root\>" passwd #在上一步的基础上以root开头的
[root@shell mnt]# grep -i "^root" passwd #同上
[root@shell mnt]# grep -i "^\<root\>$" passwd #以root开头以root结尾
[root@shell mnt]# grep -i "\<root\>$" passwd #以root结尾的
4.grep中的正则表达式
grep r... file #以r开头的任意3个字符的行
grep r...t file #以r开头,t结尾的,并且中间有任意三个字符的行
grep ..t file #以t结尾的,前面有3个字符的行
5.grep正则表达式与扩展正则表达式
- 正规的grep不支持扩展的正则表达式
- | 是用于表示或的扩展正则表达式字符,正规的grep无法识别
- 加 \ ,这个字符就被翻译成扩展的正则表达式,就像egrep和grep -E一样。
[root@shell mnt]# grep -iE "^root\>|\<root$" passwd #从开始的root和结束时
[root@shell mnt]# egrep -i "^root\>|\<root$" passwd #或者
[root@shell mnt]# grep -iE "^root\>|\<root$" passwd -v #不是以root开头和root结尾的即中间的
[root@shell mnt]# grep -iE "^root\>|\<root$" passwd -v | grep root #不是以root开头和root结尾的即中间的
[root@shell mnt]# grep -iE "^root\>|\<root$" passwd -v | grep "\<root\>"
6.grep中字符匹配次数的设定
.* | 关键字之间匹配任意字符 |
---|---|
* | 字符出现【0-任意次】 |
? | 字符出现[ 0-1]次 |
+ | 字符出现1到任意次 |
{n} | 字符出现n次 |
|{m,n} | 字符出现【最少出现m次,最多出现n次 |
{0,n} | 字符出现0到n次 |
{m,} | 字符出现至少m次 |
xy{n}xy | 关键字出现n次 |
[root@shell mnt]# grep -E "x*" test #过滤x无数次
[root@shell mnt]# grep -E "x?*" test