linux下统计目录中文件的大小,代码如下:
 
#!/bin/sh
# filename: df_dir.sh
#edit www.jb200.com
    usage(){
        echo -e "nUsage: `basename $0` DIRECTORY [MIN_SIZE]n"
        echo "Get file list of DIRECTORY, then output them in order by size."
        echo "If MIN-SIZE is specified, only print those greater than MIN-SIZE.";
        echo -e "MIN-SIZE is non-zero integer optionally followed by a k/K/m/M/g/G.n";
        exit
    }
    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
        usage
    elif [ ! -d $1 ] ; then
        echo -e "nERROR: $1 is not a directory or does not existn"
        exit
    fi
    ## delete the slash at the end of directory name
    ## eg: /usr/share/ --> /usr/share
    dir=${1%/}
    ## if MIN_SIZE is specified
    if [ -n $2 ] ; then
        ## get the last char of MIN_SIZE
        unit=${2: -1}
        ## get thE NUMBER part of MIN_SIZE except the unit
        size=${2%?}
        ## if size is not an integer number, then exit
        echo $size|awk '{if($0~/[^0-9]/) exit 1}'
        [ $? -ne 0 ] && usage
        case $unit in
            g|G)    msize=$[size * 1024 * 1024]
                    ;;
            m|M)    msize=$[size * 1024]
                    ;;
            k|K)    msize=$size
                    ;;
            [0-9])  msize=$2
                    ;;
            *)      usage
                    ;;
        esac
    else
        msize=0
    fi
    du -s $dir/*|sort -rn|awk -v size=$msize '{
        if($1>1024*1024 && $1>size) printf "%5.1fGt%sn",$1/1024/1024,$2;
        else if($1>1024 && $1>size) printf "%5.1fMt%sn",$1/1024,$2;
        else if($1>size) printf "%5dKt%sn",$1,$2}'
用法: dfdir <目录> [最小文件大小,可省略,单位可为k/K/m/M/g/G, 默认为K]
说明: 大小超过1G的文件输出单位为G,超过1M的文件输出为单位为M
例1:
例2:
例3:
个人感觉,这个shell脚本写的不错,主要是多参数的灵活应用,方便输出想要的数据格式。
有需要统计目录文件大小的朋友,建议参考下这个,肯定有帮助哦。