用法:

[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

258
218
251
[root@localhost ~]# cat 2.txt
aaa
218
316

要求:列当前目录下,文件中所有行第二字字符串为"1"的所有文件名

[root@localhost ~]# grep "^.1" *   //文件名和匹配的行

1.txt:218
2.txt:218
2.txt:316

[root@localhost ~]# grep "^.1" * -l  //只列出文件名

1.txt
2.txt

例二:

 
  1. [root@localhost ~]# cat export.part  

  2. declare -x SSH_TTY="/dev/pts/1"

  3. declare -x TERM="linux"#

  4. #declare -x USER="ROOT"

  5. #declare -x USER="aaa"#

  1. [root@localhost ~]# grep -in'root' export.part  //-i忽略大小写;-n输出相应的行号

  2. 3:#declare -x USER="ROOT"

  3. [root@localhost ~]# grep '^#' export.part  

  4. #declare -x USER="ROOT"

  5. #declare -x USER="aaa"#

  6. [root@localhost ~]# grep '#$' export.part  

  7. declare -x TERM="linux"#

  8. #declare -x USER="aaa"#

  9. [root@localhost ~]# grep '^#.*#$' export.part  

  10. #declare -x USER="aaa"#

  11. [root@localhost ~]# grep -v '^#.*#$' export.part  //-v反选搜索条件……

  12. declare -x SSH_TTY="/dev/pts/1"

  13. declare -x TERM="linux"#

  14. #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