grep
grep 管道命令
1、常用的参数
c 只输出匹配行的总数
i 不区别大小写
h 过滤多文件时不显示文件名
l 过滤多文件时只输入匹配的文件名
n 匹配行和行号
v 不包含匹配的
2、过滤出一个单词
-bash-3.2# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
3、输入匹配的行数和
-bash-3.2# grep root -c /etc/passwd
2
4、不区分大小写并以a开头的
-bash-3.2# cat 1.txt
aaaaa
AAAAA
bbbbb
BBBBB
-bash-3.2# grep '^a' -i 1.txt
aaaaa
AAAAA
5、多条件匹配
-bash-3.2# grep -e root -e ftp /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
6、反向过滤
-bash-3.2# cat 1.txt
aaaaa
AAAAA
bbbbb
BBBBB
-bash-3.2# grep -iv a 1.txt
bbbbb
BBBBB
7、以bash$结束的过滤
-bash-3.2# grep bash$ /etc/passwd
root:x:0:0:root:/root:/bin/bash
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash
nagios:x:500:500::/home/nagios:/bin/bash
test:x:501:501::/home/test:/bin/bash
8、查找出第一个小写,第二个大写,后面跟着4个小写,一个冒号,一个空格,一个数字
-bash-3.2# cat 1.txt
aZaaaa: 3
Bbb bb:b1 bb
4ccc5:ccccc
Q$d:dd:ddddd
-bash-3.2# grep '[a-z][A-Z][a-z]\{4\}\:[[:space:]][0-9]' 1.txt
aZaaaa: 3
9、匹配a或者B开头
-bash-3.2# cat 1.txt
aZaaaa: 3
Bbb bb:b1 bb
4ccc5:ccccc
Q$d:dd:ddddd
-bash-3.2# grep ^[aB] 1.txt
aZaaaa: 3
Bbb bb:b1 bb
10、 以a或者b或者c开头的
-bash-3.2# cat 1.txt
aZaaaa: 3
bbbbb
ccccc
Bbb bb:b1 bb
4ccc5:ccccc
Q$d:dd:ddddd
aa
bbbb
ccc
-bash-3.2# grep ^"\(a\|b\|c\)" 1.txt
aZaaaa: 3
bbbbb
ccccc
aa
bbbb
ccc
11、建议
学习grep之前先看下shell编程学习之正则表达式 ,这样会更容易理解和上手