grep (global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。

    在文件中搜索一个单词,命令会返回一个包含 match_pattern 的文本行

    1. grep match_pattern file_name
    2. grep "match_pattern" file_name

    在多个文件中查找

    1. grep "match_pattern" file_1 file_2 file_3 ...

    -v 反转查找

    输出除匹配之外的所有行 -v 选项

    1. grep -v "match_pattern" file_name
    2. ls | egrep -v '*\.txt'

    —color=auto 标记匹配颜色

    1. grep "match_pattern" file_name --color=auto

    -E 使用正则表达式

    1. $ grep -E "[1-9]+"
    2. # 或
    3. egrep "[1-9]+"

    -o 只输出文件中匹配到的部分

    1. $ echo this is a test line. | grep -o -E "[a-z]+\."
    2. line.
    3. $ echo this is a test line. | egrep -o "[a-z]+\."
    4. line.

    -c 统计文件或者文本中包含匹配字符串的行数

    1. grep -c "text" file_name
    2. ls | egrep -c '*\.txt'

    -n 输出包含匹配字符串的行数

    1. $ grep "text" -n file_name
    2. # 或
    3. cat file_name | grep "text" -n
    4. # 多个文件
    5. grep "text" -n file_1 file_2

    -bo 打印样式匹配所位于的字符或字节偏移

    1. $ echo gun is not unix | grep -bo "not"
    2. 7:not

    一行中字符串的字符便宜是从该行的第一个字符开始计算,起始值为0

    搜索多个文件并查找匹配文本在哪些文件中

    1. grep -l "text" file1 file2 file3... # 显示哪些文件包含搜索内容
    2. grep -bon "text" file1 file2 file3... # 同时输出行列号

    -r 在多级目录中对文本进行递归搜索

    1. grep "text" . -r -n

    -i 忽略大小写

    1. $ echo "hello world" | grep -i "HELLO"
    2. hello

    -e 指定多个匹配

    1. $ echo this is a text line | grep -e "is" -e "line" -o
    2. is
    3. line

    也可以使用 -f 选项来匹配多个样式,在样式文件中逐行写出需要匹配的字符。

    1. $ cat patfile
    2. aaa
    3. bbb
    4. echo aaa bbb ccc ddd eee | grep -f patfile -o

    -q 静默输出

    1. grep -q "test" filename
    2. #不会输出任何信息,如果命令运行成功返回0,失败则返回非0值。一般用于条件测试。

    在 grep 搜索结果中包括或者排除指定文件

    1. #只在目录中所有的.php和.html文件中递归搜索字符"main()"
    2. grep "main()" . -r --include *.{php,html}
    3. #在搜索结果中排除所有README文件
    4. grep "main()" . -r --exclude "README"
    5. #在搜索结果中排除filelist文件列表里的文件
    6. grep "main()" . -r --exclude-from filelist

    使用 0 值字节后缀的 grep 与 xargs

    1. #测试文件:
    2. echo "aaa" > file1
    3. echo "bbb" > file2
    4. echo "aaa" > file3
    5. grep "aaa" file* -lZ | xargs -0 rm
    6. #执行后会删除file1和file3,grep输出用-Z选项来指定以0值字节作为终结符文件名(\0),xargs -0 读取输入并用0值字节终结符分隔文件名,然后删除匹配文件,-Z通常和-l结合使用。

    打印出匹配文本之前或者之后的行

    1. #显示匹配某个结果之后的3行,使用 -A 选项:
    2. seq 10 | grep "5" -A 3
    3. 5
    4. 6
    5. 7
    6. 8
    7. #显示匹配某个结果之前的3行,使用 -B 选项:
    8. seq 10 | grep "5" -B 3
    9. 2
    10. 3
    11. 4
    12. 5
    13. #显示匹配某个结果的前三行和后三行,使用 -C 选项:
    14. seq 10 | grep "5" -C 3
    15. 2
    16. 3
    17. 4
    18. 5
    19. 6
    20. 7
    21. 8
    22. #如果匹配结果有多个,会用“--”作为各匹配结果之间的分隔符:
    23. echo -e "a\nb\nc\na\nb\nc" | grep a -A 1
    24. a
    25. b
    26. --
    27. a
    28. b