本文共 1088 字,大约阅读时间需要 3 分钟。
14、grep抓取文件内容中特定字符
语法:grep <-option> Keywords filename/ filedirectory
filename/ filedirectory:文件名或文件所在的绝对路径。 要匹配的关键字Keywords可以加引号,也可以不加引号。参数:
1).在a.txt文件中搜包含name的行打印出来
[root@admin t2]# grep name a.txtname is aa
2).抽取/root/install.log文件中匹配man关键字的内容
[root@admin /]# cat /root/install.log | grep -w manInstalling man-1.6f-32.el6.x86_64Installing man-pages-overrides-6.6.3-2.el6.noarchInstalling man-pages-3.22-20.el6.noarch
3).当只知道某个关键字,比如man,但不知道在哪个文件中定义的时候,可以使用grep递归的搜索
[root@admin /]# grep -r man *
上面命令中的星号’ *’ 代表的是通配当前面目录下的所有文件,也可以在具体某一个文件中搜索,如a.txt
4).使用-o进行模式匹配抽取
[root@admin tt]# grep -o 'this is' 11.txtthis isthis isthis is
5).匹配到关键name之以后,再向下打印n = 3行
[root@admin t2]# cat a.txt | grep -A 3 namenamecfwesdf12edf342sdfs
6).匹配到关键name之以后,再向上打印n = 3行
[root@admin t2]# cat a.txt | grep -B 3 nameadfasd this is the last one %234123 ^adsftgrtname
转载地址:http://xbmdi.baihongyu.com/