为什么find . -name "*.xml" | xargs grep FOO返回与文件名匹配,而find . -name "*.xml" | xargs -i -sh -c "grep FOO {}"不是?
除非在发布您的问题时出现错误,否则之前不应该使用连字符sh:
您在输出中没有获得文件名的原因grep是使用单个文件作为参数运行.要强制使用文件名输出-H.
find . -name "*.xml" | xargs -I {} sh -c "grep -H FOO {}"
Run Code Online (Sandbox Code Playgroud)
此外,-ifor xargs版本在4.2.9版本左右被弃用.你应该用-I {}.
小智 5
正如前面的答案所述,区别在于为每个文件调用 grep ,并且如果在命令行上仅指定一个文件,则 grep 不会报告文件名,除非给出 -H (--with-filename)标志。
为什么要对每个文件调用 grep?这是因为(无论喜欢与否)对 xargs 使用 -I(或 -i)标志会强制命令为每个参数运行一次,就像对 xargs 使用标志“-L 1”一样。
从手册页:
Run Code Online (Sandbox Code Playgroud)-I replace-str Replace occurrences of replace-str in the initial-arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1.