Linux shell 里的进程替换(Process Substitution)

老猫是我 · 2022-05-11 22:23:57 · 热度: 14

bash 和 zsh 里都支持进程替换(Process Substitution)

写法为:

<(command) 或 >(command)

比如:

$ cat <(ls)       #把<(ls)当一个临时文件,文件内容是ls的结果,cat这个临时文件
 
$ ls > >(cat)      #把>(cat)当成临时文件,ls的结果重定向到这个文件,最后这个文件被cat

用进程替换将 std 和 err 输出分别定向:

$ some_command > >(/bin/cmd_for_stdout) 2> >(/bin/cmd_for_stderr)

另参考这里:

http://www.ibm.com/developerworks/cn/aix/library/au-satzsh.html

里面有更多例子,比如:

#使用临时文件来将一个文件中的字段提取并重新组合到另一个文件中
$ cut -f1 fileone >t1
$ cut -f5 filetone >t5
$ paste t1 t5
 
#用进程替换可以无需临时文件完成此任务
$ paste -d: <(cut -d: -f1 /etc/passwd) <(cut -d: -f5 /etc/passwd)
 
#进程替换支持嵌套
$ sort <(egrep -v '^#' <(paste -d: <(cut -d: -f5 /etc/passwd)  <(cut -d: -f1 /etc/passwd) ) )

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册