unix中循环外变量的值

时间:2014-08-13 20:03:48

标签: bash unix

请问我尝试了很多选项,但我不知道如何在循环外使用该值,

c='0'   
find $file -type f -maxdepth 1 -iname '*.R' -print0 | while read -d '' file; do

    c=$(($c + $(wc -l < $file) )) 

done 
echo $c

非常感谢

2 个答案:

答案 0 :(得分:6)

这是因为管道在子shell中创建并处理你的while循环。在子shell中进行的所有更改都不会反映在父shell中。

使用process substitution来避免分支子shell:

while IFS= read -d '' file; do
    c=$(($c + $(wc -l < "$file") )) 
done < <(find "$file" -type f -maxdepth 1 -iname '*.R' -print0)

答案 1 :(得分:1)

如果您没有太多文件,

find "$file" -type f -maxdepth 1 -iname '*.R' -print0 |
xargs -r0 wc -l | tail -n 1

或同样

wc -l "$file"/*.[Rr] | tail -n 1

将打印总数。

find "$file" -type f -maxdepth 1 -iname '*.R' -exec wc -l {} \;|
awk '{ c += $1 } END { print c }'

适用于任意大量的文件集。

(如果您的find支持-exec +,那么请务必使用它。)