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条回答
Emotional °昔
2楼-- · 2019-03-07 15:30

du -c | awk '/./{line=$0} END{print $1}'

查看更多
走好不送
3楼-- · 2019-03-07 15:35
find -name '*.undo' -exec wc -c {} + | tail -n 1

should give the actual total number of bytes in the files, if you don't have too many files (where "too many" is going to be a really large number, probably in the thousands). Or if you just want to get the number alone,

find -name '*.undo' -exec wc -c {} + | tail -n 1 | cut -d' ' -f 1
查看更多
唯我独甜
4楼-- · 2019-03-07 15:36

Try:

find . -name "*.undo" -ls | awk '{total += $7} END {print total}'

On my system the size of the file is the seventh field in the find -ls output. If your find … -ls output is different, adjust.

In this version, using the existing directory information (file size) and the built-in ls feature of find should be efficient, avoiding process creations or file i/o.

查看更多
登录 后发表回答