bash - 在单个命令中将一个命令的输出附加到另一个命令的输出

标签 bash unix stdout pipe

有没有办法将一个命令的 stdout 输出附加到另一个命令,并将合并的输出通过管道传输到另一个命令?我曾经使用以下方法(以ack-grep为例)

# List all python, js files in different directories
ack-grep -f --py apps/ > temp
ack-grep -f --js -f media/js >> temp
cat temp | xargs somecommand

有没有一种方法可以在一条命令中做到这一点?

最佳答案

只需将两个 ack-grep 命令作为复合命令运行即可;然后管道 compund 命令的结果。 man bash 中定义的第一个复合命令是括号:

   (list) list is executed in a subshell environment (see  COMMAND  EXECU-
              TION  ENVIRONMENT below).  Variable assignments and builtin com-
              mands that affect the  shell's  environment  do  not  remain  in
              effect  after  the  command completes.  The return status is the
              exit status of list.

所以:

james@bodacious-wired:tmp$echo one > one.txt
james@bodacious-wired:tmp$echo two > two.txt
james@bodacious-wired:tmp$(cat one.txt; cat two.txt) | xargs echo
one two

您可以使用花括号来达到类似的效果,但是花括号在语法上有一些差异(例如,它们对花括号和其他单词之间需要空格更加挑剔)。最大的区别是大括号内的命令在当前 shell 环境中运行,因此它们会影响您的环境。例如:

james@bodacious-wired:tmp$HELLO=world; (HELLO=MyFriend); echo $HELLO
world
james@bodacious-wired:tmp$HELLO=world; { HELLO=MyFriend; }; echo $HELLO
MyFriend

如果你真的很喜欢,你可以定义一个函数并执行它:

james@bodacious-wired:tmp$myfunc () (
> cat one.txt
> cat two.txt
> )
james@bodacious-wired:tmp$myfunc | xargs echo
one two
james@bodacious-wired:tmp$

关于bash - 在单个命令中将一个命令的输出附加到另一个命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9108181/

相关文章:

bash - 当文件在 bash 中具有不同前缀时,如何按文件名中的日期排序?

linux - 期望登录后运行 shell 命令

java - Unix 脚本 : accessing required . 耳文件(按文件名掩码)

c - 数组性能与 LinkedList 非常相似 - 给出了什么?

python - 将标准输出重定向到 tkinter 文本小部件

python - 当程序在 python 中运行时,如何打印到控制台?

Node .js;当写入文件时,来自标准输出的彩色文本会转换为对象符号

iphone - iOS应用程序运行脚本

bash - Shell - 删除别名中变量之前的空格

linux - bash - 如何将结果从 which 命令传送到 cd