简体   繁体   English

将cat输出到bash数字变量

[英]Output of cat to bash numeric variable

I have a set of files, each containing a single (integer) number, which is the number of files in the directory of the same name (without the .txt suffix) - the result of a wc on each of the directories. 我有一组文件,每个文件包含一个(整数)数字,这是同名目录中文件的数目(不带.txt后缀)-每个目录上wc的结果。

I would like to sum the numbers in the files. 我想对文件中的数字求和。 I've tried: 我试过了:

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

But the answer is 0. If I simply echo the output of cat : 但是答案是0。如果我只是echocat的输出:

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

The values are there: 值在那里:

1313
1528
13465
22258
7262
6162
...

Presumably I have to cast the output of cat somehow? 大概我必须以某种方式投射cat的输出?

[EDIT] [编辑]

I did find my own solution in the end: 我确实找到了自己的解决方案:

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

but the accepted answer is neater as it doesn't output along the way 但可接受的答案更加整洁,因为它不会一直输出

The way you're summing the output of cat should work. 您对cat的输出求和的方式应该起作用。 However, you're getting 0 because your while loop is running in a subshell and so the variable that stores the sum goes out of scope once the loop ends. 但是,您得到0原因是while循环在子shell中运行,因此一旦循环结束,存储和的变量将超出范围。 For details, see BashFAQ/024 . 有关详细信息,请参见BashFAQ / 024

Here's one way to solve it, using process substitution (instead of pipes): 这是使用过程替换 (而不是管道)解决问题的一种方法:

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

Note that I've taken the liberty of changing the find/cat/sum operations, but your approach should work fine as well. 请注意,我已经自由更改了find / cat / sum操作,但是您的方法也应该可以正常工作。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM