用法:
[root@www ~]# grep [-acinv] [--color=auto] '搜寻字符串' filename
选项与参数:-a :将 binary 文件以 text 文件的方式搜寻数据-c :统计匹配的行数-i :忽略大小写的不同,所以大小写视为相同-n :顺便输出行号-v :反向选择,亦即显示出没有 '搜寻字符串' 内容的那一行!-o:只输出匹配的部分,单行如果多次匹配。输出每次匹配独占一行,结合wc统计
--color=auto :可以将找到的关键词部分加上颜色的显示
grep 'regex' -o | wc -l:结合wc,统计匹配的次数
-b:打印字符偏移,第一个字符从0开始
-l:小写L,打印匹配的文件名
-L:打印不匹配的文件名
-q:不输出只返回值,0匹配1不匹配
-r(-R):递归查找
-Z:grep输出以0值字节(\0)作为输出文件名终结符,结合xargs使用,和find ..-print0结合xargs操作含有空格文件的时候用法一样,-Z一般结合-l使用。
例一:
[root@localhost ~]# cat 1.txt
258218251[root@localhost ~]# cat 2.txtaaa218316要求:列当前目录下,文件中所有行第二字字符串为"1"的所有文件名
[root@localhost ~]# grep "^.1" * //文件名和匹配的行
1.txt:2182.txt:2182.txt:316[root@localhost ~]# grep "^.1" * -l //只列出文件名
1.txt2.txt例二:
[root@localhost ~]# cat export.part
declare -x SSH_TTY="/dev/pts/1"
declare -x TERM="linux"#
#declare -x USER="ROOT"
#declare -x USER="aaa"#
[root@localhost ~]# grep -in'root' export.part //-i忽略大小写;-n输出相应的行号
3:#declare -x USER="ROOT"
[root@localhost ~]# grep '^#' export.part
#declare -x USER="ROOT"
#declare -x USER="aaa"#
[root@localhost ~]# grep '#$' export.part
declare -x TERM="linux"#
#declare -x USER="aaa"#
[root@localhost ~]# grep '^#.*#$' export.part
#declare -x USER="aaa"#
[root@localhost ~]# grep -v '^#.*#$' export.part //-v反选搜索条件……
declare -x SSH_TTY="/dev/pts/1"
declare -x TERM="linux"#
#declare -x USER="ROOT"
第三:
#不显示匹配的行;只返回运行值:[root@localhost ~]# grep 'root' /etc/passwd -q;echo $?0[root@localhost ~]# grep 'roott' /etc/passwd -q;echo $?1
第四:查找时包含、排除某些文件,用通配符匹配。
[root@localhost tmp]# find../b./b/1.h./b/1.c./a./a/1.h./a/1.c[root@localhost tmp]# grep -r 'a' . --include *.c./b/1.c:abc./a/1.c:abc[root@localhost tmp]# grep -r 'a' . --exclude *.c./b/1.h:abc./a/1.h:abc[root@localhost tmp]# grep -r 'a' . --exclude-from /root/exclude.txt./b/1.c:abc./a/1.c:abc[root@localhost tmp]# cat /root/exclude.txt1.h
第五:同时返回匹配行的前n行、后n行、前n行+后n行,例:
[root@localhost tmp]# cat a.txt1234565557890[root@localhost tmp]# grep '5' a.txt -A 25655578[root@localhost tmp]# grep '5' a.txt -B 23456555[root@localhost tmp]# grep '5' a.txt -A 2 -B 2345655578[root@localhost tmp]# grep '5' a.txt -C 2345655578#多个文件匹配,以--分隔[root@localhost tmp]# cp a.txt b.txt[root@localhost tmp]# grep '5' *txt -A 2a.txt:5a.txt-6a.txt:555a.txt-7a.txt-8--b.txt:5b.txt-6b.txt:555b.txt-7b.txt-8