为什么 xargs 不替换第二个 {}

Why is xargs not replacing the second {}

我正在使用 xargs 尝试回显文件名及其内容。这是命令

find output/ -type f | xargs -I {} sh -c "echo {} ; cat {}"

但是由于某些原因,cat 之后的第二个替换没有被替换。仅适用于 一些 个文件,因此某些文件可以正常工作。

明确地说,我不是在寻找让我回显文件名及其内容的命令,我想了解为什么这个特定命令不起作用。

是否是名称中带有白色 space 的文件造成了问题?尝试添加 \",如下所示:

find output/ -type f | xargs -I {} sh -c "echo \"{}\" ; cat \"{}\""

这对我有用Bash。

事实证明该命令太长,因此它使用较短的文件名而无法使用较长的文件名。来自 man xargs

-I replstr
             Execute utility for each input line, replacing one or more occurrences of replstr in up to replacements (or 5 if no -R flag is specified) arguments to utility with the
             entire line of input.  The resulting arguments, after replacement is done, will not be allowed to grow beyond 255 bytes; this is implemented by concatenating as much
             of the argument containing replstr as possible, to the constructed arguments to utility, up to 255 bytes.  The 255 byte limit does not apply to arguments to utility
             which do not contain replstr, and furthermore, no replacement will be done on utility itself.  Implies -x.

中指出了问题的根本原因,但没有解决方案。

谷歌搜索后,我找不到解除 255 个字符限制的方法。

因此,一种可能的解决方法是使用 shell 变量作为替代。

示例:

find . | xargs -I% sh -c 'F="%";iconv -f gb2312 -t utf-8 "$F">"$F.out";mv "$F.out" "$F"'

记得在最外面的sh -c参数字符串使用单引号,我们不希望里面的$F被我们的parent shell.