我正在查找文件列表。

我如何将它输送到另一个实用程序,如cat,以便cat显示所有这些文件的内容?

然后,我将使用grep来搜索这些文件中的一些文本。


当前回答

在bash中,以下代码是合适的:

find /dir -type f -print0 | xargs -0i cat {} | grep whatever

这将找到/dir目录下的所有文件,并安全地将文件名输送到xargs中,xargs将安全地驱动grep。

如果你在/dir目录下有成千上万的文件,跳过xargs不是一个好主意;Cat将由于参数列表长度过大而中断。Xargs会帮你处理的。

-print0参数用于查找与xargs的-0参数相匹配,以正确处理带有空格的文件名。xargs的-i参数允许您在cat命令行中插入所需的文件名。括号被从find导入cat命令的文件名所取代。

其他回答

我使用的方法是这样的:

find . -name <filename> -print0 | xargs -0 cat | grep <word2search4>

"find"的"-print0"参数和"xargs"的"-0"参数需要正确处理文件路径/名称中的空白。

对我来说,听起来像是shell脚本的工作:

for file in 'find -name *.xml'
do
   grep 'hello' file
done

或者类似的东西

现代版

POSIX 2008添加了+标记来查找,这意味着它现在自动将尽可能多的文件分组到单个命令执行中,非常像xargs,但有一些优点:

您不必担心文件名中的奇数字符。 您不必担心使用零文件名调用命令。

文件名问题是在没有-0选项的xargs中出现的,“即使没有文件名也运行”问题是在没有-0选项的情况下出现的,但是GNU xargs有-r或——no-run-if-empty选项来防止这种情况发生。此外,这种表示法减少了进程的数量,并不是说您可能会度量性能上的差异。因此,你可以这样写:

find . -exec grep something {} +

经典的版本

find . -print | xargs grep something

如果您使用的是Linux,或者有GNU的find和xargs命令,那么使用-print0和find一起使用,-0和xargs一起使用来处理包含空格和其他奇怪字符的文件名。

find . -print0 | xargs -0 grep something

从grep调整结果

如果你不想要文件名(只是文本),那么在grep中添加一个适当的选项(通常是-h来抑制“标题”)。为了绝对保证grep打印文件名(即使只找到一个文件,或者最后一次调用grep只给出了一个文件名),然后在xargs命令行中添加/dev/null,这样至少会有两个文件名。

这将只递归地打印文件的名称和内容。

find . -type f -printf '\n\n%p:\n' -exec cat {} \;

编辑(改进版): 这将只递归地打印文本(ascii)文件的名称和内容。

find . -type f -exec grep -Iq . {} \; -print | xargs awk 'FNR==1{print FILENAME ":" $0; }'

再试一次

find . -type f -exec grep -Iq . {} \; -printf "\n%p:" -exec cat {} \;

Piping to another process (although this won't accomplish what you said you are trying to do): command1 | command2 This will send the output of command1 as the input of command2. -exec on a find (this will do what you want to do, but it's specific to find): find . -name '*.foo' -exec cat {} \; Everything between find and -exec are the find predicates you were already using. {} will substitute the particular file you found into the command (cat {} in this case); the \; is to end the -exec command. Send output of one process as command line arguments to another process: command2 `command1` For example: cat `find . -name '*.foo' -print` Note these are backquotes not regular quotes (they are under the tilde ~ on my keyboard). This will send the output of command1 into command2 as command line arguments. It's called command substitution. Note that file names containing spaces (newlines, etc) will be broken into separate arguments, though.