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.
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:
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?
[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
catshould work. However, you’re getting0because yourwhileloop is running in a subshell and so the variable that stores the sum goes out of scope once the loop ends. For details, see BashFAQ/024.Here’s one way to solve it, using process substitution (instead of pipes):
Note that I’ve taken the liberty of changing the find/cat/sum operations, but your approach should work fine as well.