使用xargs运行多个命令-for循环

问题描述 投票:0回答:2

基于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
bash find xargs
2个回答
0
投票

您为什么坚持使用xargs?您也可以执行以下操作。

while read -r file; do
    echo $file
done <<<$(find . -name "*.txt")

由于这是在同一shell中执行的,因此可以在循环中更改变量。否则,您将获得一个无法使用的子外壳。


0
投票

[当在脚本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
© www.soinside.com 2019 - 2024. All rights reserved.