Skip to content

Pipes — joining commands

Linux & the command line Lesson 7 2:01 English narration · English + 中文 subtitles burned in

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

Chapters

Transcript
This is the idea the command line is built on. 这就是命令行赖以建立的那个概念。
A pipe sends one command's output straight into sort, as its input. 管道把一条命令的输出直接送进 sort,作为它的输入。
Cat produces five lines; sort receives those same five lines and hands back an ordered version. cat 产出五行;sort 收到同样这五行,交回一个排好序的版本。
And notice what did not happen: no file in between. 再注意什么没有发生:中间没有文件。
Nothing was saved and re-read — the lines went directly from one program to the other. 没有东西被保存再读回来——那些行是直接从一个程序走到另一个程序的。
You can join as many as you like, like an assembly line. 你想接多少条都行,就像一条流水线。
Cat produces the lines. cat 产出那些行。
Sort puts them in order. sort 把它们排好序。
And uniq drops the repeats that are now next to each other. 而 uniq 丢掉那些现在挨在一起的重复项。
In a real terminal you would see only the last one printed — the middle lists exist for a moment and are never shown, which is exactly why they are drawn here. 在真实的终端里你只会看到最后一步打印出来的东西—— 中间那些列表只存在一瞬间,从来不会被显示出来, 而这正是它们在这里被画出来的原因。
And that middle list explains the course's most common pipe mistake. 而中间那个列表解释了这门课里最常见的管道错误。
Uniq only compares NEIGHBOURING lines. uniq 只比较相邻的行。
Run it on the raw list and it removes nothing — the two pears were never next to each other. 在原始列表上跑它,它什么都删不掉——那两个 pear 从来没有挨在一起过。
Sort them first and it works. 先把它们排序,它就管用了。
It is sort that puts them together, and uniq that then sees them as a repeat. 是 sort 把它们放到一起的,然后 uniq 才把它们看成一次重复。
Put four together and you can answer a real question: how many different fruits are in the file? 把四条接起来,你就能回答一个真实的问题: 这个文件里有多少种不同的水果?
Cat, sort, uniq, count — and the answer is three. cat、sort、uniq、计数——答案是 3。
No single command does that, and none of these four was written with your question in mind. 没有哪一条单独的命令能做到这件事, 而这四条里也没有哪一条是为你的问题写的。
That is the Unix idea: many small tools, each doing its one job, joined by pipes. 这就是 Unix 的思路:很多个小工具,每个只做一件事,用管道接起来。
Four things to take with you. 带走四点。
One: a pipe sends one command's output into the next. 第一:管道把一条命令的输出送进下一条。
Two: with no file in between. 第二:中间不落文件。
Three: order matters — sort before uniq, never after. 第三:顺序有讲究——sort 在 uniq 之前,不能反过来。
Four: each tool does one job, and pipes do the combining. 第四:每个工具只做一件事,而组合是管道干的。
Now type the tasks into the terminal below. 现在把下面那些题目敲进终端里。

Log in or create account

IGCSE, A-Level & AP