Add up a column of numbers at the Unix shell

后端 未结 20 2248
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:38

    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.

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

    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
    
    0 讨论(0)
  • 2021-01-29 18:43
    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 )
    
    0 讨论(0)
  • 2021-01-29 18:44

    Pipe to gawk:

     cat files.txt | xargs ls -l | cut -c 23-30 | gawk 'BEGIN { sum = 0 } // { sum = sum + $0 } END { print sum }'
    
    0 讨论(0)
  • 2021-01-29 18:44

    Here's mine

    cat files.txt | xargs ls -l | cut -c 23-30 | sed -e :a -e '$!N;s/\n/+/;ta' | bc
    
    0 讨论(0)
  • 2021-01-29 18:46

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