Given a list of files in files.txt
, I can get a list of their sizes like this:
cat files.txt | xargs ls -l | cut -c 23-30
which pr
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.
The whole ls -l and then cut is rather convoluted when you have stat. It is also vulnerable to the exact format of ls -l (it didn't work until I changed the column numbers for cut)
Also, fixed the useless use of cat.
<files.txt xargs stat -c %s | paste -sd+ - | bc
sizes=( $(cat files.txt | xargs ls -l | cut -c 23-30) )
total=$(( $(IFS="+"; echo "${sizes[*]}") ))
Or you could just sum them as you read the sizes
declare -i total=0
while read x; total+=x; done < <( cat files.txt | xargs ls -l | cut -c 23-30 )
If you don't care about bite sizes and blocks is OK, then just
declare -i total=0
while read s junk; total+=s; done < <( cat files.txt | xargs ls -s )
Pipe to gawk:
cat files.txt | xargs ls -l | cut -c 23-30 | gawk 'BEGIN { sum = 0 } // { sum = sum + $0 } END { print sum }'
Here's mine
cat files.txt | xargs ls -l | cut -c 23-30 | sed -e :a -e '$!N;s/\n/+/;ta' | bc
You can use the following script if you just want to use shell scripting without awk or other interpreters:
#!/bin/bash
total=0
for number in `cat files.txt | xargs ls -l | cut -c 23-30`; do
let total=$total+$number
done
echo $total