Answers:
那是因为grep
无法读取文件名以通过标准输入进行搜索。您正在做的是打印包含的文件名XYZ
。使用find
的-exec
选项代替:
find . -name "*ABC*" -exec grep -H 'XYZ' {} +
来自man find
:
-exec command ;
Execute command; true if 0 status is returned. All following
arguments to find are taken to be arguments to the command until
an argument consisting of `;' is encountered. The string `{}'
is replaced by the current file name being processed everywhere
it occurs in the arguments to the command, not just in arguments
where it is alone, as in some versions of find.
[...]
-exec command {} +
This variant of the -exec action runs the specified command on
the selected files, but the command line is built by appending
each selected file name at the end; the total number of invoca‐
tions of the command will be much less than the number of
matched files. The command line is built in much the same way
that xargs builds its command lines. Only one instance of `{}'
is allowed within the command. The command is executed in the
starting directory.
如果您不需要实际的匹配行,而只需要包含至少一个出现的字符串的文件名列表,请改用此命令:
find . -name "*ABC*" -exec grep -l 'XYZ' {} +
… | grep -R 'XYZ'
没有道理。一方面,-R 'XYZ'
意味着递归作用于XYZ
目录。另一方面,… | grep 'XYZ'
意味着要XYZ
在grep
的标准输入中查找模式。\
在Mac OS X或BSD上,grep
将被XYZ
视为一种模式,并抱怨:
$ echo XYZ | grep -R 'XYZ'
grep: warning: recursive search of stdin
(standard input):XYZ
GNU grep
不会抱怨。相反,它将视为XYZ
模式,忽略其标准输入,并从当前目录开始递归搜索。
你想做的可能是
find . -name "*ABC*" | xargs grep -l 'XYZ'
…类似于
grep -l 'XYZ' $(find . -name "*ABC*")
…两者都告诉grep
您要XYZ
在匹配的文件名中查找。
但是请注意,文件名中的任何空格都会导致这两个命令中断。您可以xargs
通过将其NUL用作分隔符来安全使用:
find . -name "*ABC*" -print0 | xargs -0 grep -l 'XYZ'
但是@terdon的解决方案使用起来find … -exec grep -l 'XYZ' '{}' +
更简单,更好。
Linux推荐:ll -iR | grep“文件名”
例如:Bookname.txt,然后使用ll -iR | grep“书名”或ll -iR | grep“名称”或ll -iR | grep“书籍”
我们可以搜索部分文件名。
这将列出当前文件夹和子文件夹中匹配的所有文件名
find
其他一些答案中所示的方法结合使用)也更加有效。