1.grep 文本过滤命令
##全面搜索研究正则表达式并显示出来
grep 命令 (Global search regular expression and print out the line)是一种强大的文本搜索工具,根据用户指定的‘模式’对目标文本进行匹配检查,打印匹配到的行。由正则表达式或者字符及基本文本字符所编写的过滤条件
(1)grep 的格式:
grep + 匹配条件 + 处理文件
例如: grep root passwd #过滤passwd中含有root的行并显示出来
grep ^root passswd #过滤passwd中以root开头行并显示出来
grep root$ passwd #过滤passwd中以root结尾行并显示出来
grep -i root passwd #过滤passwd中含有root的行且忽略大小写并显示出来
grep -E "root|ROOT" passwd #过滤passwd中含有root或者ROOT的行并显示出来
实验:(在虚拟机中)
cp /etc/passwd /mnt
ls /mnt
vim /mnt/passwd #先删除一些内容,再添加一些新的内容,方便后面的实验观察现象
cat /mnt/passwd
cd /mnt
grep root passwd #找出passwd中含有root的行
grep ^root passwd #找出passwd中以root开头行
grep -i ^root passwd #找出passwd中以root开头的行并且忽略大小写
grep root$ passwd #找出passwd中以root结尾的行
grep -E "^root|root$" passwd #过滤以root开头或以root结尾的行
egrep "^root|root$" passwd #说明 egrep 等同于 grep -E
@@显示passwd里root在中间的行
grep -i root passwd | grep -i -v -E "^root|root$" #-i表示忽略大小写
(2)grep 中正则表达式:
## . 代表一个任意字符
'r..t' #在r和t之间有2个任意字符
'r....' #在r的后面有4个任意字符
'..t' #在t的前面有2个任意字符
(3)grep中字符的匹配位置设定:
## ^ 表示以……开头 $ 表示以……结尾 \< \> 表示不做任何拓展
^root #以关键字root开头
root$ #以关键字root结尾
\<root #关键字root之前不做拓展 (精确匹配)
root\> #关键字root之后不做拓展
\<root\> #关键字root前后不做拓展
实验:
vim test
cat test
grep 'r.t' test
grep 'rt' test
grep 'r..t' test
grep '\<r..t' test
grep '\<r..t\>' test
(4)grep中字符的匹配次数设定:
* #字符出现0-任意次
\? #字符出现0-1次 ## \可以不写
\+ #字符出现1-任意次
\{n\} #字符出现n次
\{m,n\} #字符出现最少m次,最多n次