Skip to content

Searching with grep

Linux & the command line Lesson 8 1:58 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
Grep searches for a word and prints only the lines that contain it. grep 搜索一个词,只打印包含它的那些行。
Give it error and this log file, and out of five lines, one comes back. 给它 error 和这个日志文件,五行里回来一行。
On a file this small you could have read it yourself. 在这么小的文件上你自己读也行。
On a log of ten thousand lines, that is the point: grep turns a wall of text into the handful of lines that matter. 但在一个一万行的日志上,这才是重点: grep 把一堵文字墙变成了少数几行真正要紧的内容。
Grep is case-sensitive, like everything else here, and that quietly loses lines. grep 是区分大小写的,这里的一切都是, 而这会悄悄让你丢掉一些行。
Look at line four: capital E R R O R. 看第四行:大写的 ERROR。
The plain search walked past it. 普通的搜索从它旁边走过去了。
Add dash i and grep ignores case, so it catches both. 加上 -i,grep 就忽略大小写,于是两行都能抓到。
The capital line was there all along — the plain search simply did not match it, and said nothing. 那行大写的一直都在——普通搜索只是没匹配上,而且什么也没说。
Two more options earn their keep. 还有两个选项很值。
Dash n puts the line number in front of each match, so you can jump to it in an editor. -n 在每一个匹配前面加上行号,这样你可以在编辑器里跳过去。
And dash v inverts the whole thing: it prints the lines that do NOT match. 而 -v 把整件事反过来:它打印不匹配的那些行。
That is how you say "everything except" — filter out the routine lines and you are left with the surprises left over. 这就是"除了……以外的一切"的说法—— 把例行的行过滤掉,剩下的就是那些意外。
And here is where grep really earns its keep. 而这里才是 grep 真正体现价值的地方。
It takes lines in and gives lines out, which is exactly the shape a pipe wants. 它接收行、交出行,而这正是管道想要的形状。
So: read the file, filter, then count. 于是:读文件、过滤、然后计数。
How many errors were there? 到底有多少个错误?
One command, three small tools, and no file written on the way. 一条命令,三个小工具,而且中途没有写任何文件。
Four things to take with you. 带走四点。
One: grep prints only the lines containing the word. 第一:grep 只打印包含那个词的行。
Two: dash i ignores case and dash n shows the line number. 第二:-i 忽略大小写,-n 显示行号。
Three: dash v inverts it, giving the lines that do NOT match. 第三:-v 把它反过来,给出不匹配的那些行。
Four: grep is a filter, so it belongs in a pipe. 第四:grep 是一个过滤器,所以它属于管道。
Now type the tasks into the terminal below. 现在把下面那些题目敲进终端里。

Log in or create account

IGCSE, A-Level & AP