Recursively counting files in a Linux directory

后端 未结 21 1073
既然无缘
既然无缘 2020-11-28 17:17

How can I recursively count files in a Linux directory?

I found this:

find DIR_NAME -type f ¦ wc -l

But when I run this it returns

21条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 17:29

    Combining several of the answers here together, the most useful solution seems to be:

    find . -maxdepth 1 -type d -print0 |
    xargs -0 -I {} sh -c 'echo -e $(find "{}" -printf "\n" | wc -l) "{}"' |
    sort -n
    

    It can handle odd things like file names that include spaces parenthesis and even new lines. It also sorts the output by the number of files.

    You can increase the number after -maxdepth to get sub directories counted too. Keep in mind that this can potentially take a long time, particularly if you have a highly nested directory structure in combination with a high -maxdepth number.

提交回复
热议问题