5.2 使用grep搜索文本
grep是Linux下非常强大的基于行的文本搜索工具,使用该工具时,如果匹配到相关信息就会打印出符合条件的所有行。下面列出了该命令常用的参数:
- [root@localhost ~]# grep [-ivnc] '
需要匹配的字符'
文件名
#-i
不区分大小写
#-c
统计包含匹配的行数
#-n
输出行号
#-v
反向匹配
为演示grep的用法,这里首先创建一个文件,文件名和文件内容如下:
- [root@localhost ~]# cat tomAndJerry.txt The cat's name is Tom, what's the mouse's name?
The mouse's NAME is Jerry
They are good friends
下面要找出含有name的行:
- [root@localhost ~]# grep 'name' tomAndJerry.txt The cat's name is Tom, what's the mouse's name?
#
打印出含有name
的行的行编号
[root@localhost ~]# grep -n 'name' tomAndJerry.txt 1:The cat's name is Tom, what's the mouse's name?
由于grep区分大小写,所以虽然第二行中含有大写的NAME,但是也不会匹配到。如果希望忽略大小写,可以加上-i参数。
- [root@localhost ~]# grep -i 'name' tomAndJerry.txt The cat's name is Tom, what's the mouse's name?
The mouse's Name is Jerry
如果想知道文件中一共有多少包含name的行,可以使用下面的命令。注意到第二条命令和第一条命令只有一个参数的差别,但是输出的结果却是不一样的。了解了-i参数的作用就不难理解了,请读者自行区分以下两条命令的区别。
- [root@localhost ~]# grep -c 'name' tomAndJerry.txt 1
[root@localhost ~]# grep -ci 'name' tomAndJerry.txt 2
如果想打印出文件中不包含name的行,可以使用grep的反选参数-v。读者可自行区分以下命令的区别:
- [root@localhost ~]# grep -v 'name' tomAndJerry.txt The mouse's Name is Jerry
They are good friends
[root@localhost ~]# grep -vi 'name' tomAndJerry.txt They are good friends
以上命令都可以使用cat命令+管道符改写。比如上一个命令可以这样改写:
- [root@localhost ~]# cat tomAndJerry.txt | grep -vi 'name'
They are good friends