Add up a column of numbers at the Unix shell

后端 未结 20 2265
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:24

    In ksh:

    echo " 0 $(ls -l $(<files.txt) | awk '{print $5}' | tr '\n' '+') 0" | bc
    
    0 讨论(0)
  • 2021-01-29 18:25

    TMTWWTDI: Perl has a file size operator (-s)

    perl -lne '$t+=-s;END{print $t}' files.txt
    
    0 讨论(0)
  • 2021-01-29 18:26
    ... | 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.

    0 讨论(0)
  • 2021-01-29 18:36

    I would use "du" instead.

    $ cat files.txt | xargs du -c | tail -1
    4480    total
    

    If you just want the number:

    cat files.txt | xargs du -c | tail -1 | awk '{print $1}'
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-29 18:38

    Here goes

    cat files.txt | xargs ls -l | cut -c 23-30 | 
      awk '{total = total + $1}END{print total}'
    
    0 讨论(0)
提交回复
热议问题