2.1 KiB
2.1 KiB
Unix 管道
管道将两个进程连接在一起。用|字符编写的管道将一个命令的输出连接到第二个命令的输入。这是 Unix shell 的基本构件之一。
一个非常基本的例子是使用cat将文件内容输入字数统计工具wc:
$ cat <filename> | wc
以防你不知道这些命令:
- 打印文件的内容。
- 对输入的所有行、字和字节进行计数。
另一个常用的版本是wc -l,它只统计一个文件中的行数。
Thank you for reading my tutorials. I write these in my free time, and it requires a lot of time and effort. I use ads to keep writing these free articles, I hope you understand! Support me by disabling your adblocker on my website or, alternatively, buy me some coffee. It's much appreciated and allows me to keep working on this site!
让我们试试这个。首先,创建一个名为words.txt的文件,内容如下:
hello
world
python
ninja
are
you
?
3
2
1
然后运行以下命令:
$ cat words.txt | wc -l
输出应该是 10,因为文件中有 10 行。另一个例子是使用sort对文件中的单词进行排序:
$ cat words.txt | sort
?
are
hello
ninja
python
world
you
1
2
3
正如我们所看到的,来自words.txt的所有单词都被输入到sort中,由后者对它们进行排序。先标点,再数字,再字母。
好吧。这是最后一个使用管道的有问题的例子。有一个很棒的工具叫做cowsay。它会生成一张 ASCII 图片,上面是一头牛在说你喂它的东西:
$ echo "Are we going to learn anything useful?" | cowsay
________________________________________
< Are we going to learn anything useful? >
----------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
这是会给你的同事留下持久印象的东西。