基于Running multiple commands with xargs中的最高答案,我正在尝试使用find / xargs处理更多文件。为什么第一个文件1.txt在for循环中丢失?
$ ls
1.txt 2.txt 3.txt
$ find . -name "*.txt" -print0 | xargs -0
./1.txt ./2.txt ./3.txt
$ find . -name "*.txt" -print0 | xargs -0 sh -c 'for arg do echo "$arg"; done'
./2.txt
./3.txt
您为什么坚持使用xargs
?您也可以执行以下操作。
while read -r file; do
echo $file
done <<<$(find . -name "*.txt")
由于这是在同一shell中执行的,因此可以在循环中更改变量。否则,您将获得一个无法使用的子外壳。
[当在脚本example.sh
中使用for循环时,调用example.sh var1 var2 var3
将把var1
放在第一个参数中,而不是example.sh
中。当您要为每个命令处理一个文件时,请使用xargs
选项-L
:
find . -name "*.txt" -print0 | xargs -0 -L1 sh -c 'echo "$0"'
# or for a simple case
find . -name "*.txt" -print0 | xargs -0 -L1 echo