我正在查找文件列表。
我如何将它输送到另一个实用程序,如cat,以便cat显示所有这些文件的内容?
然后,我将使用grep来搜索这些文件中的一些文本。
我正在查找文件列表。
我如何将它输送到另一个实用程序,如cat,以便cat显示所有这些文件的内容?
然后,我将使用grep来搜索这些文件中的一些文本。
当前回答
我使用的方法是这样的:
find . -name <filename> -print0 | xargs -0 cat | grep <word2search4>
"find"的"-print0"参数和"xargs"的"-0"参数需要正确处理文件路径/名称中的空白。
其他回答
find命令有一个-exec参数,你可以用它来做类似的事情,你可以直接用它来做grep。
例如(从这里,其他好的例子在本页):
find . -exec grep "www.athabasca" '{}' \; -print
现代版
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,这样至少会有两个文件名。
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.
这对我很有用
find _CACHE_* | while read line; do
cat "$line" | grep "something"
done
列出并查看服务器上/ghi和/jkl目录下所有abc.def文件的内容
find /ghi /jkl -type f -name abc.def 2> /dev/null -exec ls {} \; -exec cat {} \;
要列出带有注释条目的abc.def文件并显示,请查看目录/ghi和/jkl中的这些条目
find /ghi /jkl -type f -name abc.def 2> /dev/null -exec grep -H ^# {} \;