测试数据:
[xiluhua@vm-xiluhua][~]$ cat msn.txt
aaa bbb
bbb ccc
ccc ddd
bbb eee
aaa ccc
bbb sss [xiluhua@vm-xiluhua][~]$ cat msn.bk
AAA BBB
BBB CCC
CCC DDD
BBB EEE
AAA CCC
BBB SSS [xiluhua@vm-xiluhua][~]$ cat msn3.bk
AAA BBB
BBB CCC
CCC DDD
BBB EEE
AAA CCC
BBB SSS
-i选项,不分大小写;-r选项,递归匹配;递归匹配当前目录下的包含"AAA BBB"的文件:
[xiluhua@vm-xiluhua][~]$ grep -nri "AAA BBB" .
./msn.txt::aaa bbb
./msn3.bk::AAA BBB
./msn.bk::AAA BBB
./bk/msn.bk::AAA BBB
-l选项,递归匹配当前目录下包含"AAA BBB"的文件的文件名:
[xiluhua@vm-xiluhua][~]$ grep -rl "AAA BBB" .
./msn3.bk
./msn.bk
./bk/msn.bk
-n选项,显示行号,查找文件/etc/passwd中帐号xiluhua的信息:
[xiluhua@vm-xiluhua][~]$ grep -n "xiluhua" /etc/passwd
:xiluhua:x:::xiluhua:/home/xiluhua:/bin/bash
-c选项,报告文件中模式被匹配到的次数:
[xiluhua@vm-xiluhua][~]$ grep -c "aaa" msn.txt
-e选型,或(or)的方式匹配多个字串
例如:grep –nE 'god|good' msn.txt
匹配god或者good。
[xiluhua@vm-xiluhua][~]$ ps -aux | grep -E 'USER|mem' | grep -v 'grep'
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
xiluhua 10375 0.0 0.0 317024 0 ? Ssl 9月07 0:20 memcached -d -p 11211 -m 128
^字符,匹配以字符开头的行:
root@MiWiFi-R3-srv ~ $ grep '^k' anaconda-ks.cfg
keyboard --vckeymap=us --xlayouts='us'
kexec-tools
字符$,匹配以字符结尾的行:
root@MiWiFi-R3-srv ~ $ grep 'tools$' anaconda-ks.cfg
kexec-tools