首页 Linux grep 命令
文章
取消

Linux grep 命令

grep 命令是非常常用的文本检索工具,可以从管道、文件中读取数据并根据搜索规则进行检索,还可以使用正则表达式增强检索。与 grep、awk 并称shell中文本处理的三剑客。

其用法概览如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
[root@centos uphie]# grep --help
用法: grep [选项]... PATTERN [FILE]...
在每个 FILE 或是标准输入中查找 PATTERN。
默认的 PATTERN 是一个基本正则表达式(缩写为 BRE)。
例如: grep -i 'hello world' menu.h main.c

正则表达式选择与解释:
  -E, --extended-regexp     PATTERN 是一个可扩展的正则表达式(缩写为 ERE)
  -F, --fixed-strings       PATTERN 是一组由断行符分隔的定长字符串。
  -G, --basic-regexp        PATTERN 是一个基本正则表达式(缩写为 BRE)
  -P, --perl-regexp         PATTERN 是一个 Perl 正则表达式
  -e, --regexp=PATTERN      用 PATTERN 来进行匹配操作
  -f, --file=FILE           从 FILE 中取得 PATTERN
  -i, --ignore-case         忽略大小写
  -w, --word-regexp         强制 PATTERN 仅完全匹配字词
  -x, --line-regexp         强制 PATTERN 仅完全匹配一行
  -z, --null-data           一个 0 字节的数据行,但不是空行

Miscellaneous:
  -s, --no-messages         suppress error messages
  -v, --invert-match        select non-matching lines
  -V, --version             display version information and exit
      --help                display this help text and exit

输出控制:
  -m, --max-count=NUM       NUM 次匹配后停止
  -b, --byte-offset         输出的同时打印字节偏移
  -n, --line-number         输出的同时打印行号
      --line-buffered       每行输出清空
  -H, --with-filename       为每一匹配项打印文件名
  -h, --no-filename         输出时不显示文件名前缀
      --label=LABEL         将LABEL 作为标准输入文件名前缀
  -o, --only-matching       show only the part of a line matching PATTERN
  -q, --quiet, --silent     suppress all normal output
      --binary-files=TYPE   assume that binary files are TYPE;
                            TYPE is 'binary', 'text', or 'without-match'
  -a, --text                equivalent to --binary-files=text
  -I                        equivalent to --binary-files=without-match
  -d, --directories=ACTION  how to handle directories;
                            ACTION is 'read', 'recurse', or 'skip'
  -D, --devices=ACTION      how to handle devices, FIFOs and sockets;
                            ACTION is 'read' or 'skip'
  -r, --recursive           like --directories=recurse
  -R, --dereference-recursive
                            likewise, but follow all symlinks
      --include=FILE_PATTERN
                            search only files that match FILE_PATTERN
      --exclude=FILE_PATTERN
                            skip files and directories matching FILE_PATTERN
      --exclude-from=FILE   skip files matching any file pattern from FILE
      --exclude-dir=PATTERN directories that match PATTERN will be skipped.
  -L, --files-without-match print only names of FILEs containing no match
  -l, --files-with-matches  print only names of FILEs containing matches
  -c, --count               print only a count of matching lines per FILE
  -T, --initial-tab         make tabs line up (if needed)
  -Z, --null                print 0 byte after FILE name

文件控制:
  -B, --before-context=NUM  打印以文本起始的NUM 行
  -A, --after-context=NUM   打印以文本结尾的NUM 行
  -C, --context=NUM         打印输出文本NUM 行
  -NUM                      same as --context=NUM
      --group-separator=SEP use SEP as a group separator
      --no-group-separator  use empty string as a group separator
      --color[=WHEN],
      --colour[=WHEN]       use markers to highlight the matching strings;
                            WHEN is 'always', 'never', or 'auto'
  -U, --binary              do not strip CR characters at EOL (MSDOS/Windows)
  -u, --unix-byte-offsets   report offsets as if CRs were not there
                            (MSDOS/Windows)

‘egrep’即‘grep -E’。‘fgrep’即‘grep -F’。
直接使用‘egrep’或是‘fgrep’均已不可行了。
若FILE 为 -,将读取标准输入。不带FILE,读取当前目录,除非命令行中指定了-r 选项。
如果少于两个FILE 参数,就要默认使用-h 参数。
如果有任意行被匹配,那退出状态为 0,否则为 1;
如果有错误产生,且未指定 -q 参数,那退出状态为 2。

请将错误报告给: bug-grep@gnu.org
GNU Grep 主页: <http://www.gnu.org/software/grep/>
GNU 软件的通用帮助: <http://www.gnu.org/gethelp/>

选项

-A/–after-context

-A n 展示匹配到的行的后 n 行

1
2
3
4
5
6
7
8
9
10
[root@centos uphie]# cat animal.txt
lion
cat
wolf
bear
duck
[root@centos uphie]# grep -A 2 cat animal.txt
cat
wolf
bear

-B/–before–context

-B n 展示匹配到的行的前 n 行

1
2
3
4
5
6
7
8
9
10
[root@centos uphie]# cat animal.txt
lion
cat
wolf
bear
duck
[root@centos uphie]# grep -B 2 duck animal.txt
wolf
bear
duck

-C/–context

-C n,展示匹配到的行的前后 n 行

1
2
3
4
5
6
7
8
9
10
[root@centos uphie]# cat animal.txt
lion
cat
wolf
bear
duck
[root@centos uphie]# grep -C 1 bear animal.txt
wolf
bear
duck

-c

只统计匹配的行数

1
2
3
4
5
6
7
8
[root@centos uphie]# cat animal.txt
lion
cat
wolf
bear
duck
[root@centos uphie]# grep -c o animal.txt
2

-E

使用可扩展的正则表达式。grep -E 等同于 egrep 命令。

1
2
3
4
5
6
7
8
9
[root@centos uphie]# cat books.txt
Math And Art,1200
Math And Physics,2300
Python: 1000 code samples,500

Go Bible,1000
PHP:The Best Programming Lauguage in The World,0
[root@centos uphie]#
[root@centos uphie]#

找到 math 开头的行,不区分大小写:

1
2
3
[root@centos uphie]# grep -i -E '^math' books.txt
Math And Art,1200
Math And Physics,2300

找到空行和行号:

1
2
[root@centos uphie]# grep -E '^$' books.txt -n
4:

-e

实现多个选项间的逻辑关系

1
2
3
4
5
6
7
8
9
[root@centos uphie]# cat books.txt
Math And Art,1200
Math And Physics,2300
Python: 1000 code samples,500

Go Bible,1000
PHP:The Best Programming Lauguage in The World,0
[root@centos uphie]#
[root@centos uphie]#

查询含有 Python 或 Go 的行:

1
2
3
[root@centos uphie]# grep -e Python -e Go books.txt
Python: 1000 code samples,500
Go Bible,1000

效果等同于:

1
2
3
[root@centos uphie]# grep -E "Python|Go" books.txt
Python: 1000 code samples,500
Go Bible,1000

-i/–ignore-case

-i,即 --ignore-case

不缺分大小写

1
2
3
4
5
6
7
8
[root@centos uphie]# cat animal.txt
lion
cat
wolf
bear
duck
[root@centos uphie]# grep -i CaT animal.txt
cat

-m/–max-count

-m n 匹配 n 行后停止

1
2
3
4
5
6
7
8
9
[root@centos uphie]# cat books.txt
Math And Art,1200
Math And Physics,2300
Python: 1000 code samples,500

Go Bible,1000
PHP:The Best Programming Lauguage in The World,0
[root@centos uphie]# grep -m 1 And books.txt
Math And Art,1200

-n/–line-number

显示匹配行和行号,行号从1开始。

1
2
3
4
5
6
7
8
9
[root@centos uphie]# cat animal.txt
lion
cat
wolf
bear
duck
[root@centos uphie]# grep -n o animal.txt
1:lion
3:wolf

-o/–only-matching

只输出匹配的内容。

[root@centos uphie]# cat animal.txt
lion
cat
wolf
bear
duck
[root@centos uphie]# grep -o a animal.txt
a
a

-q/–quite/–silent

安静模式,不输出任何信息,Shell脚本中常用

1
2
3
4
5
6
7
8
9
10
11
[root@centos uphie]# cat books.txt
Math And Art,1200
Math And Physics,2300
Python: 1000 code samples,500

Go Bible,1000
PHP:The Best Programming Lauguage in The World,0
[root@centos uphie]# grep -m 1 And books.txt
Math And Art,1200
[root@centos uphie]#
[root@centos uphie]# grep -m 1 And books.txt -q

-r/–recursive

递归遍历目录

1
2
3
4
5
[root@centos uphie]# grep -i "angry" games
grep: games: 是一个目录
[root@centos uphie]# grep -ri "angry" games
games/game1.txt:Angry Pigs
games/game2.txt:Angry Birds2

-v

排除匹配结果。

1
2
3
4
5
6
7
8
9
10
11
[root@centos uphie]# cat animal.txt
lion
cat
wolf
bear
duck
[root@centos uphie]# grep -v wolf animal.txt
lion
cat
bear
duck

-x/–line-regexp

以行为单位进行检索,匹配整行。

1
2
3
4
5
6
7
8
[root@centos uphie]# cat goods.txt
Mac
Macbook
Thinkbook E12
MacbookPro 2022
Macbook 2021
[root@centos uphie]# grep -x Macbook goods.txt
Macbook

-w/–word-regexp

以词为单位进行检索,匹配整个单词。

默认是以行为单位检索:

1
2
3
4
5
6
7
8
9
10
11
[root@centos uphie]# cat goods.txt
Mac
Macbook
Thinkbook E12
MacbookPro 2022
Macbook 2021
[root@centos uphie]# grep Mac goods.txt
Mac
Macbook
MacbookPro 2022
Macbook 2021

指定以词为单位进行检索:

1
2
3
[root@centos uphie]# grep -w Macbook goods.txt
Macbook
Macbook 2021
本文由作者按照 CC BY 4.0 进行授权