列出一个目录,包括子目录,文件数和累积大小

Udh*_*mar 5 command-line ls disk-usage

有没有办法列出目录的内容,包括具有文件计数和累积大小的子目录?

我想看看:

  • 目录数
  • 子目录数
  • 文件数
  • 累积规模

ter*_*don 6

如果我理解正确,这会给你想要的:

find /path/to/target -type d | while IFS= read -r dir; do 
  echo -ne "$dir\tsize: $(du -sh "$dir" | cut -f 1)" 
  echo -ne "\tsubdirs: $(find "$dir" -mindepth 1 -type d | wc -l)"
  echo -e "\tfiles: $(find "$dir" -type f | wc -l )";
done  | tac
Run Code Online (Sandbox Code Playgroud)

/boot例如,如果你运行它,你会得到这样的输出:

/boot/burg/themes/sora_extended size: 8.0K  subdirs: 0  files: 1
/boot/burg/themes/radiance/images   size: 196K  subdirs: 0  files: 48
/boot/burg/themes/radiance  size: 772K  subdirs: 1  files: 53
/boot/burg/themes/winter    size: 808K  subdirs: 0  files: 35
/boot/burg/themes/icons size: 712K  subdirs: 0  files: 76
/boot/burg/themes   size: 8.9M  subdirs: 26 files: 440
/boot/burg/fonts    size: 7.1M  subdirs: 0  files: 74
/boot/burg  size: 20M   subdirs: 29 files: 733
/boot/grub/locale   size: 652K  subdirs: 0  files: 17
/boot/grub  size: 4.6M  subdirs: 1  files: 224
/boot/extlinux/themes/debian-wheezy/extlinux    size: 732K  subdirs: 0  files: 11
/boot/extlinux/themes/debian-wheezy size: 1.5M  subdirs: 1  files: 22
/boot/extlinux/themes   size: 1.5M  subdirs: 2  files: 22
/boot/extlinux  size: 1.6M  subdirs: 3  files: 28
/boot/  size: 122M  subdirs: 36 files: 1004
Run Code Online (Sandbox Code Playgroud)

要轻松访问此命令,您可以将其转换为函数。将这些行添加到 shell 的初始化文件(~/.bashrc对于 bash):

dirsize(){
    find "$1" -type d | while IFS= read -r dir; do 
    echo -ne "$dir\tsize: $(du -sh "$dir"| cut -f 1)" 
    echo -ne "\tsubdirs: $(find "$dir" -mindepth 1 -type d | wc -l)"
    echo -e "\tfiles: $(find "$dir" -maxdepth 1 -type f | wc -l )";
    done  | tac
}
Run Code Online (Sandbox Code Playgroud)

您现在可以将其作为dirsize /path/.


解释

上面的函数有5个主要部分:

  1. find /path/to/target -type d | while IFS= read -r dir; do ... ; done:这将找到所有目录/path/to/target并通过将变量设置dir为其名称来处理每个目录。在IFS=确保这不会在其名称中的空格打破目录。

  2. echo -ne "$dir\tsize: $(du -sh "$dir" | cut -f 1)":这使用该命令du来获取目录的大小并cut仅打印du.

  3. echo -ne "\tsubdirs: $(find "$dir" -mindepth 1 -type d | wc -l)":此 find 命令查找$dir. 在type -d我们只找目录,确保,没有文件和-mindepth确保我们不指望当前目录,.

  4. echo -e "\tfiles: $(find "$dir" -maxdepth 1 -type f | wc -l)";: 这个查找直接( ) 下的文件 ( -type f) 。它不会计算.-maxdepth 1$dir$d

  5. | tac: 最后,整个事情都通过了tac,只是颠倒了打印行的顺序。这意味着目标目录的总大小将显示为最后一行。如果这不是您想要的,只需删除| tac.