Calculate size of files in shell

2019-03-07 14:45发布

I'm trying to calculate the total size in bytes of all files (in a directory tree) matching a filename pattern just using the shell. This is what I have so far:

find -name *.undo -exec stat -c%s {} \; | awk '{total += $1} END {print total}'

Is there an easier way to do this? I feel like there should be a simple du or find switch that does this for me but I can't find one.

To be clear I want to total files matching a pattern anywhere under a directory tree which means

du -bs *.undo

won't work because it only matches the files in the current directory.

标签: linux shell
15条回答
孤傲高冷的网名
2楼-- · 2019-03-07 15:25
find -name '*.undo' -print0 | du -hc --files0-from=- | tail -n 1

Put together from gerdemb's and strager's contributions. Using du -cb should display bytes.

查看更多
虎瘦雄心在
3楼-- · 2019-03-07 15:27

Check the du (disk usage) command.

查看更多
爷、活的狠高调
4楼-- · 2019-03-07 15:29

With zsh, you can use extended globbing to do:

du -c **/*.undo

查看更多
We Are One
5楼-- · 2019-03-07 15:29

How about this simple one.

find ./ -name *.undo | xargs wc
查看更多
来,给爷笑一个
6楼-- · 2019-03-07 15:30

I use du command like this to get the number only:

du file_list | awk '{s+=$1} END {print s}'
查看更多
乱世女痞
7楼-- · 2019-03-07 15:30

Or, you can just do this:

dir=$1

for file in $dir/* ; do

 length_file=`stat -c %s $file`
 echo "File $file has length $length_file"
 length_total=`expr $length_total + $length_file`

done

echo "Total length: $length_total ."

Where stat displays a file or file system status. The argument -c means using the specified format instead of the default one, and the format sequence $s allows the display of the total size of bytes.

expr 

Just evaluates an expression.

查看更多
登录 后发表回答