查找过程中的文件替换和计数

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

我只想知道下面的代码片段是否也可以将与find命令匹配的文件数分配到total变量中?

total=0
counter=1
while IFS= read -r -d '' file; do
    echo "process file $counter of $total"
done < <(find . -iname "*.txt" -type f -print0 | sort -zn)

注意:在循环上方执行find命令,然后计算总数并在循环中使用其结果,这是一种有效的方法吗?

bash while-loop process substitution counting
1个回答
0
投票

我假设您想在while逐个文件循环。但是,我们无法确定$total的值直到while循环结束,只要我们增加循环中的值即可。

或者,您可以先创建一个文件数组,然后进行迭代在知道$total值的文件上。

您可以尝试以下操作:

mapfile -d "" -t files < <(find . -iname "*.txt" -type f -print0 | sort -zn)
total="${#files[@]}"
for file in "${files[@]}"; do
    ((++counter))
    echo "process file $counter of $total"
    # do something with $file
done

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.