Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add up a column of numbers at the Unix shell

Tags:

linux

shell

unix

... | paste -sd+ - | bc

is the shortest one I've found (from the UNIX Command Line blog).

Edit: added the - argument for portability, thanks @Dogbert and @Owen.


Here goes

cat files.txt | xargs ls -l | cut -c 23-30 | 
  awk '{total = total + $1}END{print total}'

cat will not work if there are spaces in filenames. here is a perl one-liner instead.

perl -nle 'chomp; $x+=(stat($_))[7]; END{print $x}' files.txt

Instead of using cut to get the file size from output of ls -l, you can use directly:

$ cat files.txt | xargs ls -l | awk '{total += $5} END {print "Total:", total, "bytes"}'

Awk interprets "$5" as the fifth column. This is the column from ls -l that gives you the file size.


python3 -c"import os; print(sum(os.path.getsize(f) for f in open('files.txt').read().split()))"

Or if you just want to sum the numbers, pipe into:

python3 -c"import sys; print(sum(int(x) for x in sys.stdin))"