Searching with grep · 用 grep 搜索
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Finding text with grep
grepsearches for a word and prints only the lines that contain it:
- Out of a huge log, you instantly see just the lines that matter.
中文
用 grep 查找文本
grep搜索一个词,只打印包含它的那些行:
grep error log.txt
- 在一份庞大的日志里,你立刻就能只看到要紧的那几行。
English
Useful options
-iignores case (soErrormatcheserror).-nshows the line number of each match.-vinverts — show lines that do not match.
中文
实用选项
-i忽略大小写(于是Error也能匹配error)。-n显示每个匹配所在的行号。-v反向 —— 显示不匹配的行。
grep -n ok log.txt
English
grep loves pipes
grepshines at the end of a pipe, filtering another command's output:
- "How many error lines?" — filter to errors, then count them. A everyday combo.
中文
grep 与管道是绝配
grep放在管道末尾时最为出彩,用来过滤另一个命令的输出:
cat log.txt | grep error | wc -l
- “有多少行错误?” —— 先过滤出错误,再计数。这是日常的经典组合。
English
Common mistakes
grep pattern filefinds matching lines; add-ito ignore case.- Quote a pattern that has spaces or special characters.
中文
常见错误
grep pattern file找出匹配的行;加-i忽略大小写。- 带空格或特殊字符的模式要加引号。
Explore · 探索
grep inside a pipeline · 管道中的 grep
grep filters a stream — feed it the output of another command. · grep 过滤数据流——把另一个命令的输出喂给它。
Show only the lines of log.txt that contain error, using grep error log.txt. · 用 grep error log.txt,只显示 log.txt 中包含 error 的行。
How many errors are there? Pipe grep into · 生成 wc -l: grep error log.txt | wc -l. · 一共有多少个错误?把 grep 接到 wc -l:grep error log.txt | wc -l。