Bash TreeSize 脚本 - 改进了输出对齐

Bash TreeSize Script - improved output alignment

给出下面的脚本

#/bin/sh
echo
echo treesize of `pwd` at `date +"%Y-%m-%d %H:%M:%S"`
echo

du -k --max-depth=1 | sort -nr | awk '
BEGIN {
    split("KB,MB,GB,TB", Units, ",");
}

{
    u = 1;
    while ( >= 1024) {
             =  / 1024;
            u += 1
    }

     = sprintf("% *d%.1f %s", (7-length(sprintf("%.1f", ))), 0, , Units[u]);
    print [=11=];
}
'
echo

获得以下输出:

 treesize of /home/jonathan at 2020-04-08 10:18:50

 0295.4 GB .
 0175.6 GB ./Documents
 0118.5 GB ./vmware
  047.9 MB ./Desktop
  032.0 KB ./Pictures
  012.0 KB ./Videos
   04.0 KB ./.Public

请问如何删除前导 0 并用空格代替? 欣赏剧本!归功于互联网上的某人:)

使用sed

sed 's#^[[:space:]]*0# #g'

^ -- 行首
[[:space:]] <- Space 字符
* <-- 0 次或多次出现

#/bin/sh
echo
echo treesize of `pwd` at `date +"%Y-%m-%d %H:%M:%S"`
echo

du -k --max-depth=1 | sort -nr | awk '
BEGIN {
    split("KB,MB,GB,TB", Units, ",");
}

{
    u = 1;
    while ( >= 1024) {
             =  / 1024;
            u += 1
    }

     = sprintf("% *d%.1f %s", (7-length(sprintf("%.1f", ))), 0, , Units[u]);
    print [=11=];
}' | sed 's#^[[:space:]]*0# #g'
echo

设法找到问题:将 sprintf 命令中的 0 替换为“ ”。

#/bin/sh
echo
echo treesize of `pwd` at `date +"%Y-%m-%d %H:%M:%S"`
echo

du -k --max-depth=1 | sort -nr | awk '
BEGIN {
    split("KB,MB,GB,TB", Units, ",");
}

{
    u = 1;
    while ( >= 1024) {
             =  / 1024;
            u += 1
    }

     = sprintf("%8.1f %s", , Units[u]);
    print [=10=];
}'
echo

现在显示:

treesize of /home/jonathan at 2020-04-08 11:03:29

   295.5 GB .
   175.6 GB ./Documents
   118.5 GB ./vmware
  1003.7 MB ./.cache
   268.1 MB ./.config
    47.9 MB ./Desktop
    32.0 KB ./Pictures
    12.0 KB ./Videos
     4.0 KB ./.Templates
     4.0 KB ./.Public
     4.0 KB ./Music
     4.0 KB ./Downloads

尽情享受吧!