14、grep抓取文件内容中特定字符
语法:grep <-option> Keywords filename/ filedirectory
filename/ filedirectory:文件名或文件所在的绝对路径。
要匹配的关键字Keywords可以加引号,也可以不加引号。
参数:
- -E : 扩展的grep,支持复杂正则
- -w : 加上单词的界定,也就是说只有完全匹配给定的单词的行才能被抓取出来
- -F : 完全关闭正则
- -v : 显示不匹配的项
- -i : 不区分大小写
- -o : 只显示匹配内容(模式匹配,给定什么显示什么)
- -r : 递归参数(会递归遍历目录下的所有文件,包括二级目录、三级目录等下所有的文件)
- -A : 搜出关键字以后,还可以向下打印指定的行数,后面接要打印的行数
- -B :搜出关键字以后,还可以向上打印指定的行数,后面接要打印的行数
1).在a.txt文件中搜包含name的行打印出来
[root@admin t2]# grep name a.txt
name is aa
2).抽取/root/install.log文件中匹配man关键字的内容
[root@admin /]# cat /root/install.log | grep -w man
Installing man-1.6f-32.el6.x86_64
Installing man-pages-overrides-6.6.3-2.el6.noarch
Installing 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.txt
this is
this is
this is
5).匹配到关键name之以后,再向下打印n = 3行
[root@admin t2]# cat a.txt | grep -A 3 name
name
cfwesdf
12edf
342sdfs
6).匹配到关键name之以后,再向上打印n = 3行
[root@admin t2]# cat a.txt | grep -B 3 name
adfasd this is the last one %
234123 ^
adsftgrt
name
7)匹配成功后,进行剪切操作
将找到的字符串通过cut命令以空格剪切开,并取第二个区域的
[root@admin tody]# grep this a.txt | cut -d " " -f 2
is
[root@admin tody]# cat a.txt |grep this
this is a test
[root@admin tody]# cat a.txt |grep this | cut -d " " -f 2
is