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:15
du -c *pattern*

This will print the total on the last line of output.

查看更多
Deceive 欺骗
3楼-- · 2019-03-07 15:17

I have been looking at this problem too (only a year later...) - only just found this page.

Something that I found works (for me) is the following:

find /mnt/iso -name *.avi -printf "%s\n" | paste -sd+ - | bc

This will return the total size of all the .avi files in all the sub-folders below /mnt/iso

I have to give credit to radoulov for the paste command - see this page: Shell command to sum integers, one per line?

Just to add - just in case a folder matches the search term - it's a good idea to use -type f in the find command too.

查看更多
唯我独甜
4楼-- · 2019-03-07 15:17

I think the version with xargs could be imroved (simplified) ls -1 *.undo | xargs wc

查看更多
一夜七次
5楼-- · 2019-03-07 15:18
find -name *.undo -print0 | du -hc --files0-from=-
查看更多
走好不送
6楼-- · 2019-03-07 15:22

Perl one-liner:

find . -name "*.undo" -ls | perl -lane '$t += $F[6]; END{print $t}'

The @F autosplit array starts at index $F[0] while awk fields start with $1, hence $F[6] is used instead of awk's $7

查看更多
姐就是有狂的资本
7楼-- · 2019-03-07 15:24

Python is part of most linux distributions.

import os
import fnmatch
size= 0
for path, dirs, files in os.walk( '.' ):
    for f in files:
        if fnmatch.fnmatch(f,'*.py'):
            fileSize= os.path.getsize( os.path.join(path,f) ) 
            print f, fileSize
            size += fileSize
print size

Longish, but perfectly clear and highly extensible.

查看更多
登录 后发表回答