Add up a column of numbers at the Unix shell

后端 未结 20 2246
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:19

    Pure bash

    total=0; for i in $(cat files.txt | xargs ls -l | cut -c 23-30); do 
    total=$(( $total + $i )); done; echo $total
    
    0 讨论(0)
  • 2021-01-29 18:19

    If you have R, you can use:

    > ... | Rscript -e 'print(sum(scan("stdin")));'
    Read 4 items
    [1] 2232320
    

    Since I'm comfortable with R, I actually have several aliases for things like this so I can use them in bash without having to remember this syntax. For instance:

    alias Rsum=$'Rscript -e \'print(sum(scan("stdin")));\''
    

    which let's me do

    > ... | Rsum
    Read 4 items
    [1] 2232320
    

    Inspiration: Is there a way to get the min, max, median, and average of a list of numbers in a single command?

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

    I like to use....

    echo "
    1
    2
    3 " | sed -e 's,$, + p,g' | dc 
    

    they will show the sum of each line...

    applying over this situation:

    ls -ld $(< file.txt) | awk '{print $5}' | sed -e 's,$, + p,g' | dc 
    

    Total is the last value...

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

    In my opinion, the simplest solution to this is "expr" unix command:

    s=0; 
    for i in `cat files.txt | xargs ls -l | cut -c 23-30`
    do
       s=`expr $s + $i`
    done
    echo $s
    
    0 讨论(0)
  • 2021-01-29 18:23
    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))"
    
    0 讨论(0)
  • 2021-01-29 18:24

    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
    
    0 讨论(0)
提交回复
热议问题