带有多个命令的xargs

use*_*654 11 bash xargs

在当前目录中,我想打印文件名和内容.我可以单独打印文件名或内容

find . | grep "file_for_print" | xargs echo
find . | grep "file_for_print" | xargs cat
Run Code Online (Sandbox Code Playgroud)

但我想要的是将它们打印在一起,如下所示:

file1
line1 inside file1
line2 inside file1
file2
line1 inside file2
line2 inside file2
Run Code Online (Sandbox Code Playgroud)

我读了多个命令的xargs作为参数 并尝试过

find . | grep "file_for_print" | xargs -I % sh -c 'echo; cat;'
Run Code Online (Sandbox Code Playgroud)

但不起作用.我不熟悉xargs,所以不知道究竟是什么"-I%sh -c"的意思.谁能帮助我?谢谢!

nec*_*cer 22

find . | grep "file_for_print" | xargs -I % sh -c 'echo %; cat %;'(OP失踪了%)

  • 正是我要找的!谢谢! (2认同)
  • 此解决方案适用于 Linux,但不适用于 Macos (mojave)。 (2认同)

ric*_*ici 14

首先,几乎没有区别:

find . | grep "file_for_print" | xargs echo
Run Code Online (Sandbox Code Playgroud)

find . -name "file_for_print*"
Run Code Online (Sandbox Code Playgroud)

除了第二个不匹配的文件名this_is_not_the_file_for_print,它将打印每行一个文件名.它也会快得多,因为它不需要生成和打印整个递归目录结构,只是为了让grep将大部分内容扔掉.

find . -name "file_for_print*"
Run Code Online (Sandbox Code Playgroud)

实际上是完全一样的

find . -name "file_for_print*" -print
Run Code Online (Sandbox Code Playgroud)

其中-print动作打印每一个匹配的文件名,然后换行.如果您未提供find任何操作,则假定您需要-print.但它有更多的伎俩.例如:

find . -name "file_for_print*" -exec cat {} \;
Run Code Online (Sandbox Code Playgroud)

-exec操作导致find执行以下命令,直到\;替换{}为每个匹配的文件名.

find并不局限于单一行动.无论你想要多少,你都可以告诉它.所以:

find . -name "file_for_print*" -print -exec cat {} \;
Run Code Online (Sandbox Code Playgroud)

你可能会做得很好.

有关此非常有用的实用程序的更多信息,请键入:

man find
Run Code Online (Sandbox Code Playgroud)

要么

info find
Run Code Online (Sandbox Code Playgroud)

并阅读所有关于它.

  • +1可能是最温和的交付rtfm ;-) (6认同)

dsh*_*erd 10

因为它还没有被说出来:-I %告诉xargs用你给它的命令中的参数替换'%'.这sh -c '...'意味着'...'在新shell中运行命令.

所以

xargs -I % sh -c 'echo %; cat %;'
Run Code Online (Sandbox Code Playgroud)

将运行echo [filename]后跟cat [filename]每个文件名给出xargs.echo和cat命令将在不同的shell进程中执行,但这通常无关紧要.您的版本无法正常工作,因为它缺少%传递给命令的符号xargs.


为了它的价值,我会用这个命令来实现同样的目的:

find -name "*file_for_print*" | parallel 'echo {}; cat {};'
Run Code Online (Sandbox Code Playgroud)

因为它更简单(parallel自动{}用作替换字符,默认情况下可以使用多个命令).