# Grep

**Grep** 是一个命令行工具，用于在输入文件中搜索匹配正则表达式或固定字符串的行，并打印出匹配的行。它由[肯·汤普森](https://www.edgepedia.org/zh/ken-thompson)（Ken Thompson）在[贝尔实验室](https://www.edgepedia.org/zh/bell-labs)（Bell Labs）编写，是将 `ed` 文本编辑器的 `g/re/p` 命令提取出来而成的独立程序，最早出现于第四版 AT&T UNIX，如今已由 POSIX 标准化，并随几乎所有类 Unix 系统一同发布。<sup>[1](https://thingshavehistory.com/posts/ed/)</sup><sup> • </sup><sup>[2](https://obsdman.cs.toronto.edu/grep.1)</sup>

| 关键事实 | 详情 |
|---|---|
| 名称 | 源自 `ed` 命令 `g/re/p`：全局匹配正则表达式并打印每个匹配行<sup>[1](https://thingshavehistory.com/posts/ed/)</sup> |
| 首次出现 | 第四版 AT&T UNIX<sup>[2](https://obsdman.cs.toronto.edu/grep.1)</sup> |
| 模式语法 | 基本正则表达式（BRE）、扩展正则表达式（ERE）和 Perl 兼容正则表达式（PCRE）；在 GNU grep 中，BRE 与 ERE 的匹配能力相同<sup>[3](https://www.gnu.org/s/grep/manual/grep.html)</sup> |
| 退出状态 | 若选中了行则为 0，若未选中任何行则为 1，若发生错误则为 2<sup>[4](https://www.gnu.org/s/grep/manual/html_node/Exit-Status.html)</sup> |
| 当前 GNU 版本 | 3.12，发布于 2025 年 4 月 10 日<sup>[5](https://lists.gnu.org/archive/html/info-gnu/2025-04/msg00008.html)</sup> |
| 许可证 | 基于 GNU 通用公共许可证第 3 版或更高版本的自由软件<sup>[6](https://www.gnu.org/software/grep/)</sup> |
| 著名后继者 | ripgrep、ugrep、The Silver Searcher 和 ack，它们增加了并行搜索和默认过滤功能<sup>[7](https://github.com/burntsushi/ripgrep)</sup> |

## 起源

这个名字记录了它的来历。在汤普森 1969 年为 Unix 编写的行编辑器 `ed` 中，调用 `g/re/p` 的含义是：全局地（`g`），对每一行匹配正则表达式（`re`）的文本，打印（`p`）出来。贝尔实验室的程序员们太频繁地使用这个片段，以至于汤普森将其提取为一个独立程序，并以该命令为其命名。<sup>[1](https://thingshavehistory.com/posts/ed/)</sup> 据道格·麦克罗伊（Doug McIlroy）回忆，是他请汤普森做这个分离工作的，而汤普森第二天早上就把完成的程序放在了他的桌上。<sup>[8](https://unix.stackexchange.com/questions/115780/regex-pattern-g-and-ed-g-pattern-which-came-first-and-why-g)</sup>

grep 从 `ed` 中带出的正则表达式引擎有着更悠久的谱系。汤普森在将这一形式体系引入 `ed` 之前，曾在 MIT 的 CTSS 系统上的 QED 编辑器中实现了斯蒂芬·克莱尼（Stephen Kleene）1951 年提出的正则表达式记法。<sup>[9](https://mart.traagel.dev/blog/what-does-grep-stand-for/)</sup> 通过 grep、`sed`、`awk` 以及后来的各种语言，这一记法成为标准的 Unix 词汇。<sup>[1](https://thingshavehistory.com/posts/ed/)</sup>《Research UNIX 读本》（*A Research UNIX Reader*）称 grep 常被视为软件工具的典范——它诞生于汤普森被要求将表达式识别器从 `ed` 中分离出来之时，并以 `g/re/p` 命令命名。<sup>[10](https://citeseerx.ist.psu.edu/document?doi=42723b1b7024d0fddf7222bd64e961442f08a7af&repid=rep1&type=pdf)</sup>

## 基本行为

POSIX 的语法概要为 `grep [OPTION]... PATTERNS [FILE]...`。Grep 在每个文件中搜索模式，并打印出每一个匹配行；文件参数为 `-` 表示标准输入，若未给出文件，则非递归搜索读取标准输入，而递归搜索检查工作目录。<sup>[11](https://www.man7.org/linux/man-pages/man1/grep.1.html)</sup> 在 shell 命令中使用 grep 时，模式通常需要加引号，因为包含 `*` 或 `[` 等 shell 元字符的未加引号模式可能在 grep 看到它之前就被 shell 展开。<sup>[12](https://www.shellcheck.net/wiki/SC2062)</sup>

常用选项控制什么算作匹配以及打印什么：`-i` 忽略大小写，`-v` 反转匹配以选择不匹配的行，`-w` 将匹配限制为整词，`-n` 在输出前加上从 1 开始的行号，`-c` 打印每个文件的匹配行数，`-l` 仅打印包含匹配的文件名，并在首次匹配时停止扫描每个文件。<sup>[11](https://www.man7.org/linux/man-pages/man1/grep.1.html)</sup> 上下文选项 `-A`、`-B` 和 `-C` 在每个匹配之后、之前或周围打印选定数量的行。<sup>[13](https://man.freebsd.org/cgi/man.cgi?manpath=FreeBSD+Ports+13.0&query=grep&sektion=1)</sup>

退出状态遵循 `cmp` 和 `diff` 等程序的惯例，其中状态 1 并非错误：0 表示至少选中了一行，1 表示没有选中任何行，2 表示发生了错误，如文件缺失或模式无效。这使得 grep 在 shell 脚本中可用作是或否的测试。<sup>[4](https://www.gnu.org/s/grep/manual/html_node/Exit-Status.html)</sup>

## 正则表达式方言

Grep 理解三种正则表达式语法：基本正则表达式（BRE），默认选中，也可用 `-G` 选择；扩展正则表达式（ERE），用 `-E` 选择；以及 Perl 兼容正则表达式（PCRE），在编译了 PCRE 支持的情况下用 `-P` 选择。<sup>[11](https://www.man7.org/linux/man-pages/man1/grep.1.html)</sup> 在 GNU grep 中，基本正则表达式和扩展正则表达式仅仅是同一模式匹配功能的不同记法；PCRE 具有不同的功能，记录在 pcre2syntax(3) 和 pcre2pattern(3) 手册页中。<sup>[3](https://www.gnu.org/s/grep/manual/grep.html)</sup> `-F` 选项将模式解释为固定字符串而非正则表达式，这是字面搜索的正确选择。<sup>[11](https://www.man7.org/linux/man-pages/man1/grep.1.html)</sup>

方言之间的历史分裂反映了 1970 年代小型计算机上的原始分工：`egrep` 是使用扩展正则表达式的变体，`fgrep` 是搜索固定字符串的变体。POSIX 在 1992 年认定它们已过时，2001 年将其移除，GNU Grep 2.5.3 在 2007 年弃用它们，GNU Grep 3.8 在 2022 年将其改为发出过时警告；它们计划最终被移除。<sup>[3](https://www.gnu.org/s/grep/manual/grep.html)</sup>

## 文件、目录与二进制数据

递归搜索通过 `-r`（`--recursive`）或 `-R`（`--dereference-recursive`）选择；两者在符号链接处理上不同，`-R` 跟随所有符号链接。默认情况下，设备在命令行中指定时或使用 `-R` 时会被读取，而在 `-r` 下递归遇到时会被跳过。<sup>[14](https://www.gnu.org/s/grep/manual/html_node/File-and-Directory-Selection.html)</sup> `--include`、`--exclude` 和 `--exclude-dir` 选项通过通配符模式过滤要搜索的文件。<sup>[14](https://www.gnu.org/s/grep/manual/html_node/File-and-Directory-Selection.html)</sup>

Grep 期望在文本上进行匹配，但除了可用内存外，对行长度不施加任何限制。除非使用 `-a`（`--binary-files=text`）选项，否则输入中的[空字符](https://www.edgepedia.org/zh/null-character)或输出中的编码错误会导致 GNU grep 将该文件视为二进制文件，并抑制关于匹配的详细信息，通常只报告某个二进制文件匹配。<sup>[3](https://www.gnu.org/s/grep/manual/grep.html)</sup>

## 性能

根据 GNU 手册，grep 采用的匹配算法是实现细节，可能因版本而异；然而，手册指出，在可能的情况下，单个固定模式使用博耶-摩尔（Boyer–Moore）快速[字符串搜索算法](https://www.edgepedia.org/zh/string-searching-algorithm)进行匹配，而多个固定模式则用 [Aho–Corasick 算法](https://www.edgepedia.org/zh/aho-corasick-algorithm)处理。<sup>[15](https://www.gnu.org/s/grep/manual/html_node/Performance.html)</sup>

专门化的后继工具以可移植性为代价换取大型代码库上的速度。在一项搜索 [Linux 内核](https://www.edgepedia.org/zh/linux-kernel)源码树（约 2500 万行，约 900 MB）中模式 `[A-Z]+_SUSPEND` 的基准测试中，ripgrep 在 0.082 秒内完成，git grep 在 0.273 秒内完成，ugrep 在 0.301 秒内完成，GNU grep 在 0.671 秒内完成，均启用了递归搜索和行号。<sup>[16](https://ripgrep.dev/benchmarks/)</sup> Ripgrep 的速度来自跨 CPU 核心的并行目录遍历、SIMD 加速的字面匹配、内存映射 I/O，以及在打开文件之前跳过二进制、隐藏和 git 忽略的文件。<sup>[17](https://ripgrep.dev/docs/faq/)</sup> 其维护者、软件工程师安德鲁·加兰特（Andrew Gallant）指出，grep 仍然是可移植脚本的正确选择，因为它符合 POSIX 标准并存在于每个 Unix 系统上，而 ripgrep 不符合任何此类标准。<sup>[17](https://ripgrep.dev/docs/faq/)</sup>

## 标准化与现状

POSIX 定义了 grep 的行为，包括 `-E`、`-F`、`-c`、`-l` 和 `-q` 选项，标准开发者声明了将三种历史性 grep 合并为单一命令的明确意图。<sup>[18](https://www.open-std.org/jtc1/sc22/open/n4217.pdf)</sup> GNU grep 是基于 GNU 通用公共许可证第 3 版或更高版本的自由软件，当前稳定版本为 3.12（2025 年 4 月 10 日）。<sup>[6](https://www.gnu.org/software/grep/)</sup><sup> • </sup><sup>[5](https://lists.gnu.org/archive/html/info-gnu/2025-04/msg00008.html)</sup> 在第四版 Unix 半个世纪之后，该工具仍然是类 Unix 系统的默认组件，也是管道、脚本乃至基于 ripgrep 风格搜索构建的代码补全系统检索方案中的常见构建块。<sup>[19](https://arxiv.org/abs/2601.23254)</sup>

## References

1. [ed: the editor that still ships with every Unix, Things Have History](https://thingshavehistory.com/posts/ed/)
2. [grep(1), OpenBSD manual pages](https://obsdman.cs.toronto.edu/grep.1)
3. [GNU Grep 3.12 manual](https://www.gnu.org/s/grep/manual/grep.html)
4. [Exit Status, GNU Grep 3.12 manual](https://www.gnu.org/s/grep/manual/html_node/Exit-Status.html)
5. [grep-3.12 released [stable], GNU info-gnu mailing list](https://lists.gnu.org/archive/html/info-gnu/2025-04/msg00008.html)
6. [Grep, GNU Project, Free Software Foundation](https://www.gnu.org/software/grep/)
7. [BurntSushi/ripgrep on GitHub](https://github.com/burntsushi/ripgrep)
8. [Regex `/pattern/g` and ed `:g/pattern/`: which came first, and why `g`?, Unix & Linux Stack Exchange](https://unix.stackexchange.com/questions/115780/regex-pattern-g-and-ed-g-pattern-which-came-first-and-why-g)
9. [What does grep stand for, and the seventy-five-year history of the regular expression, Mart Traagel](https://mart.traagel.dev/blog/what-does-grep-stand-for/)
10. [A Research UNIX Reader, CiteSeerX](https://citeseerx.ist.psu.edu/document?doi=42723b1b7024d0fddf7222bd64e961442f08a7af&repid=rep1&type=pdf)
11. [grep(1), Linux manual page, man7.org](https://www.man7.org/linux/man-pages/man1/grep.1.html)
12. [ShellCheck SC2062: Quote the grep pattern so the shell won't interpret it](https://www.shellcheck.net/wiki/SC2062)
13. [grep(1), FreeBSD Ports 13.0 Manual Pages](https://man.freebsd.org/cgi/man.cgi?manpath=FreeBSD+Ports+13.0&query=grep&sektion=1)
14. [File and Directory Selection, GNU Grep 3.12 manual](https://www.gnu.org/s/grep/manual/html_node/File-and-Directory-Selection.html)
15. [Performance, GNU Grep 3.12 manual](https://www.gnu.org/s/grep/manual/html_node/Performance.html)
16. [ripgrep Benchmarks: Speed Comparison vs grep, ag, ack](https://ripgrep.dev/benchmarks/)
17. [ripgrep FAQ](https://ripgrep.dev/docs/faq/)
18. [P1003.1 D3, POSIX draft, Open Group](https://www.open-std.org/jtc1/sc22/open/n4217.pdf)
19. [GrepRAG: An Empirical Study and Optimization of Grep-Like Retrieval for Code Completion, arXiv](https://arxiv.org/abs/2601.23254)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Development tools and collaboration infrastructure › Build, deployment, and development tooling

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/grep

English original: https://www.edgepedia.org/grep
