Pipes — joining commands
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
核心思想:管道
- 这正是 shell 强大的原因。管道
|把一个命令的输出,直接送进下一个命令:
cat fruits.txt | sort
cat产生这些行;sort接收它们并排好序。中间不需要任何文件。
搭一条流水线
- 你可以像装配线一样,串联任意多个命令:
cat fruits.txt | sort | uniq
sort把各行排序,然后uniq去掉相邻的重复行 —— 于是每种水果只剩一次。
小工具,大成果
- 每个命令把一件事做好。管道让你把它们组合起来,回答真实的问题:
cat fruits.txt | sort | uniq | wc -l
- “一共有多少种不同的水果?” —— 排序、去重,再计数。这就是 Unix 之道。
常见错误
|把一个命令的输出送入下一个。- 顺序很重要:
sort | uniq,不能反过来。
探索
Pipes join commands
A pipe feeds one command's 输出 into the next's 输入.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Send the output of cat fruits.txt 生成 wc -l with a pipe |, to count the lines.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
List each fruit once, in order. Pipe sort 生成 uniq: cat fruits.txt | sort | uniq.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
How many lines of fruits.txt say apple? Pipe the matching lines from grep 生成 wc -l.