【问题标题】:Running multiple commands with xargs - for loop使用 xargs 运行多个命令 - for 循环
【发布时间】:2020-05-16 06:38:03
【问题描述】:

基于Running multiple commands with xargs 中的最佳答案,我正在尝试使用 find / xargs 来处理更多文件。为什么for循环中缺少第一个文件1.txt?

$ 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


    【解决方案1】:

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

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

    因为这是在同一个 shell 中执行的,所以可以在循环中更改变量。否则你会得到一个不起作用的子shell。

    【讨论】:

    • 当文件名中有换行符时,文件名被分成两部分。这可能是print0 的原因。
    【解决方案2】:

    当您在脚本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
    

    【讨论】:

      猜你喜欢
      • 2011-10-20
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2022-08-22
      • 2020-02-05
      • 2015-12-12
      相关资源
      最近更新 更多