calculate total used disk space by files older tha

2019-03-14 23:30发布

I am trying to find the total disk space used by files older than 180 days in a particular directory. This is what I'm using:

    find . -mtime +180 -exec du -sh {} \;

but the above is quiet evidently giving me disk space used by every file that is found. I want only the total added disk space used by the files. Can this be done using find and exec command ?

Please note I simply don't want to use a script for this, it will be great if there could be a one liner for this. Any help is highly appreciated.

5条回答
仙女界的扛把子
2楼-- · 2019-03-14 23:50

Why not this?

find /path/to/search/in -mtime +180 -print0 | du -hc --files0-from - | tail -n 1
查看更多
老娘就宠你
3楼-- · 2019-03-14 23:57

@PeterT is right. Almost all these answers invoke a command (du) for each file, which is very resource intensive and slow and unnecessary. The simplest and fastest way is this:

find . -type f -mtime +356 -printf '%s\n' | awk '{total=total+$1}END{print total/1024}'
查看更多
等我变得足够好
4楼-- · 2019-03-15 00:00

The previous answer is nice, but it has one problem: it sums the same disk usage several times because it takes into account the directory disk usage.

For example, I have a lot of files in my ~/tmp directory:

$ du -sh ~/tmp
3,7G    /home/rpet/tmp

Running the first part of example posted by devnull to find the files modified in the last 24 hours, we can see that awk will sum the whole disk usage of the ~/tmp directory:

$ find ~/tmp -mtime 0 -exec du -ks {} \; | cut -f1
3849848
84
80

But there is only one file modified in that period of time, with very little disk usage:

$ find ~/tmp -mtime 0
/home/rpet/tmp
/home/rpet/tmp/kk
/home/rpet/tmp/kk/test.png

$ du -sh ~/tmp/kk
84K /home/rpet/tmp/kk

So we need to take into account only the files and exclude the directories:

$ find ~/tmp -type f -mtime 0 -exec du -ks {} \; | cut -f1 | awk '{total=total+$1}END{print total/1024}'
0.078125

You can also specify date ranges using the -newermt parameter. For example:

$ find . -type f -newermt "2014-01-01" ! -newermt "2014-06-01"

See http://www.commandlinefu.com/commands/view/8721/find-files-in-a-date-range

查看更多
手持菜刀,她持情操
5楼-- · 2019-03-15 00:05

du wouldn't summarize if you pass a list of files to it.

Instead, pipe the output to cut and let awk sum it up. So you can say:

find . -mtime +180 -exec du -ks {} \; | cut -f1 | awk '{total=total+$1}END{print total/1024}'

Note that the option -h to display the result in human-readable format has been replaced by -k which is equivalent to block size of 1K. The result is presented in MB (see total/1024 above).

查看更多
Deceive 欺骗
6楼-- · 2019-03-15 00:17

You can print file size with find using the -printf option, but you still need awk to sum.

For example, total size of all files older than 365 days:

find . -type f -mtime +356 -printf '%s\n' \
     | awk '{a+=$1;} END {printf "%.1f GB\n", a/2**30;}'
查看更多
登录 后发表回答