I want to add and echo the sum of several files using shell script. How do I start? I have a list of them like that:
$ stat /etc/*.conf | grep Size | cut -f4 -d' '
123
456
789
101112
Also something like can do the work (with awk)
stat -c "%s" /etc/*.conf|awk '{s+=$1} END {print s}'
:)
stat -c "%s" /etc/*.conf|paste -sd+|bc -l
paste utility that can be applied to a larger class of problems: separating a bunch of stuff with a delimiter. Another example is "unwrapping" (removing the line breaks from) a text file: paste -sd$' ' inputfile.
bc{ stat -c '%s+\' /etc/*.conf ; echo 0 ; } | bc
stat format adds a + sign and a continuation character after each size 0 is appended at the end to close the dangling final +The most straightforward way is to use du -bc:
$ du -bc /etc/*.conf
5139 /etc/man_db.conf
393 /etc/nsswitch.conf
5532 total
If you need to extract only the number of bytes, pipe the output to awk:
$ du -bc /etc/*.conf | awk 'END { print $1 }'
5532
--apparent-size option may be needed to use apparent sizes.
awk line also strips off the total
You can do this …
total=0
for s in $(stat /etc/*.conf | grep Size | cut -f4 -d' '); do
total=$(expr $total + $s)
done
echo total > my_file.txt, right? And what if I want to output the errors too what do I do then?
du?duwill calculate also subdirectoriesdu -b /etc/*.conf