将cat输出为bash数值变量

时间:2011-11-17 11:41:59

标签: linux bash casting numeric cat

我有一组文件,每个文件都包含一个(整数)数字,这是同名目录中的文件数(不带.txt后缀) - wc开启的结果每个目录。

我想对文件中的数字求和。我试过了:

i=0; 
find -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | while read j; do i=$i+`cat $j.txt`; done
echo $i

但答案是0.如果我只是echo cat的输出:

i=0; find -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | while read j; do echo `cat $j.txt`; done

价值观在那里:

1313
1528
13465
22258
7262
6162
...

据推测,我必须以某种方式投射cat的输出?

[编辑]

我最终找到了自己的解决方案:

i=0; 
for j in `find -mindepth 1 -maxdepth 1 -type d -printf '%f\n'`; do 
    expr $((i+=$(cat $j.txt))); 
done; 

28000
30250
...
...
647185
649607

但是接受的答案是整洁的,因为它不会沿途输出

2 个答案:

答案 0 :(得分:4)

你总结cat输出的方式应该有效。但是,您得到0因为您的while循环正在子shell中运行,因此一旦循环结束,存储总和的变量就会超出范围。有关详细信息,请参阅BashFAQ/024

这是解决问题的一种方法,使用process substitution(而不是管道):

SUM=0
while read V; do
    let SUM="SUM+V" 
done < <(find -mindepth 1 -maxdepth 1 -type d -exec cat "{}.txt" \;)

请注意,我冒昧地改变了find / cat / sum操作,但你的方法也应该正常工作。

答案 1 :(得分:1)

我的单线解决方案无需查找:

echo $(( $(printf '%s\n' */ | tr -d / | xargs -I% cat "%.txt" | tr '\n' '+')0 ))
相关问题