输入输出(Shell基础教程17.html)
Process Substitution
在上一节中,我们已经看到了如何将一个命令的输出链接到下一个命令。
但是,如果要将两个或多个命令的输出链接到另一个命令,该怎么办?
如果您有一个将文件作为参数但又想处理发送到该文件的内容的命令,该怎么办?
进程替换允许使用文件名引用进程的输入或输出。
它有两种形式:输出<(cmd.html)和输入>(cmd.html)。
示例:
输出
假设您有两个要比较其内容的文件。如果没有对行进行排序,则使用diff file1 file2可能会产生误报。
因此,如果要比较这些文件,可以创建两个有序的新文件,然后进行比较。它看起来像:
sort file1 > sorted_file1
sort file2 > sorted_file2
diff sorted_file1 sorted_file2
使用流程替换,您可以在一行中完成:
diff <(sort file1.html) <(sort file2.html)
输入
假设您要将应用程序的日志存储到文件中,同时在控制台上将其打印出来。一个非常方便的命令是tee。
echo "Hello, world!" | tee /tmp/hello.txt
现在,假设您只想在文件中使用小写字符,但在输出中保留常规大小写。
您可以通过以下方式使用流程替换:
echo "Hello, world!" | tee >(tr '[:upper:]' '[:lower:]' > /tmp/hello.txt)
Exercise
本节没有练习。
- Hello, World!(Shell基础教程1.html)
- 变量(Shell基础教程2.html)
- 将参数传递给脚本(Shell基础教程3.html)
- 数组(Shell基础教程4.html)
- 数组比较(Shell基础教程5.html)
- 基本运算符(Shell基础教程6.html)
- 基本字符串操作(Shell基础教程7.html)
- 逻辑表达式(Shell基础教程8.html)
- 循环(Shell基础教程9.html)
- shell函数(Shell基础教程10.html)
- 特殊变量(Shell基础教程11.html)
- 字符串操作(Shell基础教程12.html)
- 捕捉信号命令(Shell基础教程13.html)
- 文件测试(Shell基础教程14.html)
- 输入参数解析(Shell基础教程15.html)
- 管道(Shell基础教程16.html)
- 输入输出(Shell基础教程17.html)
- 常用表达(Shell基础教程18.html)
- 特殊命令sed(Shell基础教程19.html)
版权声明:本文为原创文章,版权归 戴老师的博客 所有,转载请联系博主获得授权。
本文地址:https://tushu.info/archives/archives-shu-ru-shu-chu-Shell-ji-chu-jiao-cheng.html
如果对本文有什么问题或疑问都可以在评论区留言,我看到后会尽量解答。
暂无标签