【问题标题】:Finding the number of files in a directory for all directories in pwd查找 pwd 中所有目录的目录中的文件数
【发布时间】:2010-06-19 11:56:50
【问题描述】:

我正在尝试列出所有目录并将其文件数量放在它旁边。

我可以找到文件总数ls -lR | grep .*.mp3 | wc -l。但是我怎样才能得到这样的输出:

dir1 34 
dir2 15 
dir3 2 
...

如果无法在屏幕上显示此信息,我不介意写入文本文件或 CSV 以获取此信息。

感谢大家对此的任何帮助。

【问题讨论】:

    标签: linux bash shell command-line


    【解决方案1】:

    假设您位于某些子目录可能包含 mp3 文件的目录中,这似乎有效。它省略了*目录。它将按包含的 mp3 文件的最大数量顺序列出目录。

    find . -mindepth 2 -name \*.mp3 -print0| xargs -0 -n 1 dirname | sort | uniq -c | sort -r | awk '{print $2 "," $1}'
    

    我使用 print0 对此进行了更新,以处理带有空格和其他棘手字符的文件名,并打印适合 CSV 的输出。

    【讨论】:

    • 我得到一个额外的 . 计数,除非我这样做 xargs -I{} -n 1 dirname \{\}
    • 你有什么操作系统和版本? -mindepth 2 应该消除.。我正在运行 Ubuntu 10.04 GNU find 4.4.2。这个命令不包括我的.。我在. 中测试了有无 mp3 文件
    • +1 我正在寻找类似但递归的东西(超过 1 级文件夹深度)。
    【解决方案2】:
    find . -type f -iname '*.mp3' -printf "%h\n" | uniq -c
    

    或者,如果顺序(dir-> count 而不是 count-> dir)对您来说真的很重要:

    find . -type f -iname '*.mp3' -printf "%h\n" | uniq -c | awk '{print $2" "$1}'
    

    【讨论】:

    • 如果没有sort,它可以多次列出某些目录。您的 awk 命令可以简化为 awk '{print $2, $1}' 或者您可以像这样执行 OP 的逗号分隔样式:awk '{print $2","$1}'
    • 我最终使用了:find / -type f -printf "%h\n" | sort | uniq -c | sort -r -n | head 额外排序以确保 uniq 对每个人都计数一次。第二个sort是按数字排序,反向-head给你TOP10
    【解决方案3】:

    可能有更好的方法,但这似乎可行。

    把它放在一个shell脚本中:

    #!/bin/sh
    for f in *
    do
      if [ -d "$f" ]
      then
          cd "$f"
          c=`ls -l *.mp3 2>/dev/null | wc -l`
          if test $c -gt 0
          then
              echo "$f $c"
          fi
          cd ..
      fi
    done
    

    【讨论】:

    • 太棒了!这对我来说是最好的答案,因为它允许我在目录和数字之间轻松添加逗号,这样我就可以将它用作 CSV 文件在 excel 中查看并在屏幕上查看。谢谢乔恩。 :)
    【解决方案4】:

    使用 Perl:

    perl -MFile::Find -le'
      find { 
        wanted => sub {
          return unless /\.mp3$/i;
          ++$_{$File::Find::dir};
          }
        }, ".";
      print "$_,$_{$_}" for 
        sort { 
          $_{$b} <=> $_{$a} 
          } keys %_;
      '
    

    【讨论】:

      【解决方案5】:

      这是处理包含异常(但合法)字符的文件名的另一种方法,例如换行符、...:

      # count .mp3 files (using GNU find)
      find . -xdev -type f -iname "*.mp3" -print0 | tr -dc '\0' | wc -c
      
      # list directories with number of .mp3 files
      find "$(pwd -P)" -xdev -depth -type d -exec bash -c '
        for ((i=1; i<=$#; i++ )); do
          d="${@:i:1}"
          mp3s="$(find "${d}" -xdev -type f -iname "*.mp3" -print0 | tr -dc "${0}" | wc -c )"
          [[ $mp3s -gt 0 ]] && printf "%s\n" "${d}, ${mp3s// /}"
        done
      ' "'\\0'" '{}' +
      

      【讨论】:

        最近更新 更多