Add up a column of numbers at the Unix shell

后端 未结 20 2287
Happy的楠姐
Happy的楠姐 2021-01-29 18:10

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

20条回答
  •  醉酒成梦
    2021-01-29 18:37

    cat files.txt | awk '{ total += $1} END {print total}'
    

    You can use the awk to do the same it even skips the non integers

    $ cat files.txt
    1
    2.3
    3.4
    ew
    1
    
    $ cat files.txt | awk '{ total += $1} END {print total}'
    7.7
    

    or you can use ls command and calculate human readable output

    $ ls -l | awk '{ sum += $5} END  {hum[1024^3]="Gb"; hum[1024^2]="Mb"; hum[1024]="Kb"; for (x=1024^3; x>=1024; x/=1024) { if (sum>=x) { printf "%.2f %s\n",sum/x,hum[x]; break; } } if (sum<1024) print "1kb"; }'
    15.69 Mb
    
    $ ls -l *.txt | awk '{ sum += $5} END  {hum[1024^3]="Gb"; hum[1024^2]="Mb"; hum[1024]="Kb"; for (x=1024^3; x>=1024; x/=1024) { if (sum>=x) { printf "%.2f %s\n",sum/x,hum[x]; break; } } if (sum<1024) print "1kb"; }'
    2.10 Mb
    

提交回复
热议问题