75 lines
2.1 KiB
Markdown
75 lines
2.1 KiB
Markdown
# Unix 管道
|
||
|
||
> 原文:[https://python.land/the-unix-shell/unix-pipes](https://python.land/the-unix-shell/unix-pipes)
|
||
|
||
管道将两个进程连接在一起。用`|`字符编写的管道将一个命令的输出连接到第二个命令的输入。这是 Unix shell 的基本构件之一。
|
||
|
||
一个非常基本的例子是使用`cat`将文件内容输入字数统计工具`wc`:
|
||
|
||
```py
|
||
$ 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](https://www.buymeacoffee.com/pythonland)**. It's much appreciated and allows me to keep working on this site!
|
||
|
||
让我们试试这个。首先,创建一个名为`words.txt`的文件,内容如下:
|
||
|
||
```py
|
||
hello
|
||
world
|
||
python
|
||
ninja
|
||
are
|
||
you
|
||
?
|
||
3
|
||
2
|
||
1
|
||
```
|
||
|
||
然后运行以下命令:
|
||
|
||
```py
|
||
$ cat words.txt | wc -l
|
||
```
|
||
|
||
输出应该是 10,因为文件中有 10 行。另一个例子是使用`sort`对文件中的单词进行排序:
|
||
|
||
```py
|
||
$ cat words.txt | sort
|
||
?
|
||
are
|
||
hello
|
||
ninja
|
||
python
|
||
world
|
||
you
|
||
1
|
||
2
|
||
3
|
||
```
|
||
|
||
正如我们所看到的,来自`words.txt`的所有单词都被输入到`sort`中,由后者对它们进行排序。先标点,再数字,再字母。
|
||
|
||
好吧。这是最后一个使用管道的有问题的例子。有一个很棒的工具叫做`cowsay`。它会生成一张 ASCII 图片,上面是一头牛在说你喂它的东西:
|
||
|
||
```py
|
||
$ echo "Are we going to learn anything useful?" | cowsay
|
||
________________________________________
|
||
< Are we going to learn anything useful? >
|
||
----------------------------------------
|
||
\ ^__^
|
||
\ (oo)\_______
|
||
(__)\ )\/\
|
||
||----w |
|
||
|| ||
|
||
```
|
||
|
||
这是会给你的同事留下持久印象的东西。 |