Shell:列出按文件计数排序的目录(包括在子目录中)

Ric*_*lis 10 unix linux shell command-line

我几乎达到了Linux主目录中允许的文件数量限制,我很好奇所有文件的位置.

在任何目录中,我可以使用例如find . -type f | wc -l显示该目录及其子目录中有多少文件的计数,但我想要的是能够生成所有子目录(和子子目录等)的完整列表每一个计数包含的所有文件,子目录-如果可以通过数排名,降.

例如,如果我的文件结构如下所示:

Home/
  file1.txt
  file2.txt
  Docs/
    file3.txt
    Notes/
      file4.txt
      file5.txt
    Queries/
      file6.txt
  Photos/
    file7.jpg
Run Code Online (Sandbox Code Playgroud)

输出将是这样的:

7  Home
4  Home/Docs
2  Home/Docs/Notes
1  Home/Docs/Queries
1  Home/Photos
Run Code Online (Sandbox Code Playgroud)

任何建议都非常感谢.(也是对答案的快速解释,所以我可以从中学习!).谢谢.

ajt*_*rds 26

我使用以下命令

find . -xdev -type f | cut -d "/" -f 2 | sort | uniq -c | sort -n

产生的东西如下:

[root@ip-***-***-***-*** /]# find . -xdev -type f | cut -d "/" -f 2 | sort | uniq -c | sort -n
      1 .autofsck
      1 stat-nginx-access
      1 stat-nginx-error
      2 tmp
     14 boot
     88 bin
    163 sbin
    291 lib64
    597 etc
    841 opt
   1169 root
   2900 lib
   7634 home
  42479 usr
  80964 var
Run Code Online (Sandbox Code Playgroud)


sag*_*agi 8

这应该工作:

find ~ -type d -exec sh -c "fc=\$(find '{}' -type f | wc -l); echo -e \"\$fc\t{}\"" \; | sort -nr
Run Code Online (Sandbox Code Playgroud)

说明:在上面的命令中将运行"find~-type d"来查找home-directory的所有子目录.对于它们中的每一个,它运行一个简短的shell脚本,找到该子目录中的文件总数(使用您已经知道的"find $ dir -type f | wc -l"命令),并将回显该数字后跟目录名称.然后运行sort命令以按降序排列文件总数.

这不是最有效的解决方案(你最终会多次扫描同一个目录),但我不确定你能用一个班轮做得更好:-)


gle*_*man 4

countFiles () {
    # call the recursive function, throw away stdout and send stderr to stdout
    # then sort numerically
    countFiles_rec "$1" 2>&1 >/dev/null | sort -nr
}

countFiles_rec () {
    local -i nfiles 
    dir="$1"

    # count the number of files in this directory only
    nfiles=$(find "$dir" -mindepth 1 -maxdepth 1 -type f -print | wc -l)

    # loop over the subdirectories of this directory
    while IFS= read -r subdir; do

        # invoke the recursive function for each one 
        # save the output in the positional parameters
        set -- $(countFiles_rec "$subdir")

        # accumulate the number of files found under the subdirectory
        (( nfiles += $1 ))

    done < <(find "$dir" -mindepth 1 -maxdepth 1 -type d -print)

    # print the number of files here, to both stdout and stderr
    printf "%d %s\n" $nfiles "$dir" | tee /dev/stderr
}


countFiles Home
Run Code Online (Sandbox Code Playgroud)

产生

7 Home
4 Home/Docs
2 Home/Docs/Notes
1 Home/Photos
1 Home/Docs/Queries
Run Code Online (Sandbox Code Playgroud)