grep命令的用法
grep:基于行的文本搜索工具
#比如说,file的内容是:
[root@localhost ~]$ cat filename
this is a textline for test
this filename is filename
just for Test
基本用法
# 比如 需要列出某文件中包含字符串'test'的行,命令:
[root@localhost ~]$ cat filename|grep 'test'
this is a textline for test
# 直接使用grep+字符串+文件名做匹配 和上面命令效果是一样的
[root@localhost ~]$ grep 'test' filename
this is a textline for test
# 列出当前文件夹下所有含'test'字符串的文件名和其匹配行
[root@localhost ~]$ grep 'test' ./*
./filename:this is a textline for test
# 列出包含字符串'name'的文件名
[root@localhost ~]$ ls |grep 'name'
filename
# 列出包含字符串'name'的进程
[root@localhost ~]$ ps -ef |grep 'name'
-i 不区分大小写
# grep 搜索默认区分大小写,还可以加上-i参数不区分大小写
[root@localhost ~]$ cat filename|grep -i 'test'
this is a textline for test
just for Test
-v 反选
# grep 还可以加上-v参数 表示反选
[root@localhost ~]$ cat filename|grep -v 'test'
this filename is filename
just for Test
[root@localhost ~]$ cat filename|grep -vi 'test'
this filename is filename
-n 输出行号
[root@localhost ~]$ cat filename|grep -v 'test'
2:this filename is filename
3:just for Test
-c 统计匹配的行数
# 同一行多次匹配 不重复计数。只计匹配到的行的个数
[root@localhost ~]$ cat filename|grep -n 'file'
1
结合sort还可以对结果进行排序
# sort 默认按字符大小比较来排序 -r表示逆序
# sed -n取消全部输出
# sed -n '2p'表示仅输出第2行,'1,3p'则输出1-3行
[root@localhost ~]$ grep -i 'test' ./* |sort -r |sed -n '2p'
./filename:this is a textline for test