1. 搜索包含特定模式的文本行:

    grep "pattern" filename

  2. 也可以像下面从stdin中读取:

    echo -e "This is a word. \n next line ." |grep word

  3. 单个grep命令也可以对多个文件进行搜索:

    grep "match_text" file1 file2 file3 ...

  4. 用--color选项可以在输出行中着重标记匹配到的单词:

     grep word filename --color=auto

  5. grep 命令只解释match_text中的某些特殊字符串。如果需要是用正则表达式,需要添加-E选项,或者使用egrep 。

    grep -E "[a-z]+" filename

    egrep "[a-z]+" filename

  6. 只输出文件中匹配到的文本内容,可以使用选项-o:

    echo "This is a line ." | egrep -o "[a-z]+."

  7. 要打印除包含match_pattern行之外的所有行,可使用:

    grep -v match_pattern file

  8. 统计文件或文本中包含匹配字符串的行数:

    grep -c "text" filename

    echo -e "1 2 3 4\nhello\n5 6" |egrep -c "[0-9]"

  9. 要文件中拥挤匹配项的数量,可以使用如下的技巧:

    echo -e "1 2 3 4 \nhello\n5 6"|egrep -o "[0-9]" |wc -l

  10. 打印出包含匹配字符串的行号:

    cat sample1.txt

    gun is not unix

    linux is fun

    bash is art

    cat sample2.txt

    planetlinux

    grep linux -n sample1.txt sample2.txt

  11. 打印模式匹配所位于的字符或字节偏移:

    echo gun is not unix |  grep -b -o "not"

  12. 搜索多个文件并找出匹配文本位于哪一个文件中:

    grep -l linux sample1.txt sample2.txt

  13. 忽略样式中大小写

    echo Hello world |grep -i "hello"

  14. 在grep搜索中指定或排除文件

    目录中递归搜索所有的.c和.cpp文件

    grep "main()" . -r --include *.{c,cpp}

    在搜索中排除所有README文件:

    grep "main()" . -r --exclude "README"

    如果需要排除目录,可以使用--exclude-dir 选项。

    如果需要从文件中读取所需排除的文件列表,使用--exclude-from FILE

  15. 使用0值字节作为后缀

    echo 'text' > file1
    echo 'cool' > file2
    echo 'text' > file3
    grep "text" file* -lZ |xargs -0 rm

  16. 打印匹配某个结果之后的前3行,使用-A选项:

    seq 10 |grep 5 -A 3

    打印匹配某个结果之后的后3行,使用-B选项:

    seq 10 |grep 5 -B 3

    打印匹配某个结果之后的后3行,使用-C选项:

    seq 10 |grep 5 -C 3