unix 输出3个最大目录和3个最大子目录

aor9mmx1  于 2023-02-22  发布在  Unix
关注(0)|答案(1)|浏览(189)

我是unix新手,我想学习unix。有人给了我这个脚本。

#!/bin/bash

top3()
{
    awk '{
        pos=index( $0, "/" ) ;
        if( pos >0 ){
            print substr($0, pos) ;
        } ;
    }'
}

TMP=`basename "$0" ".sh" `

du -sh /var/* 2>>/dev/null | sort -hr >${TMP}.dirs
cat ${TMP}.dirs

head -3 ${TMP}.dirs | top3 >${TMP}.dirs3

rm -f ${TMP}.subdirs3
for dir in $( cat ${TMP}.dirs3 )
do
    echo -e "Doing '${dir}' ..."
    grep "${dir}"'$' ${TMP}.dirs >>${TMP}.subdirs3

    du -sh ${dir}/* 2>>/dev/null | sort -hr >${TMP}.subdirs
    head -3 ${TMP}.subdirs | awk '{ printf("\t%s\n", $0) }' >>${TMP}.subdirs3

    echo "" >>${TMP}.subdirs3
done
echo ""
cat ${TMP}.subdirs3

基本上我想输出3个最大的目录和它的3个最大的子目录和我有一个困难的时间来理解脚本。有人能帮助简化这一点吗?谢谢提前
我尝试将路径从var更改为log,结果显示
error
我希望有一个更简单的剧本。

3vpjnl9f

3vpjnl9f1#

下面是一个更简单、可读性更强的解决方案:

#!/bin/bash
    
{
    du -sh /var/log/*/ |
        sort -rh |
        tee /dev/stderr |
        while read du path; do
            printf -- '\n%s\n' "Processing $du $path"
            du -sh "$path"* | sort -rh | head -3
            ((++c==3)) && break
        done
} 2>&1
示例输出
1,4G    /var/log/journal/
1,2M    /var/log/installer/
456K    /var/log/apt/
144K    /var/log/lightdm/
60K     /var/log/cups/
4,0K    /var/log/ntpstats/

Processing 1,4G /var/log/journal/
1,4G    /var/log/journal/2a7428458da7474c81169e4d51424f0c

Processing 1,2M /var/log/installer/
496K    /var/log/installer/initial-status.gz
384K    /var/log/installer/syslog
300K    /var/log/installer/partman

Processing 456K /var/log/apt/
148K    /var/log/apt/term.log
104K    /var/log/apt/eipp.log.xz
92K     /var/log/apt/term.log.3.gz
性能
# time bash old.sh
real    0m3,063s
user    0m0,548s
sys     0m2,474s

对比分析

# time bash new.sh
real    0m0,012s
user    0m0,018s
sys     0m0,005s

相关问题