Recursively counting files in a Linux directory

后端 未结 21 1115
既然无缘
既然无缘 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:44

    With bash:

    Create an array of entries with ( ) and get the count with #.

    FILES=(./*); echo ${#FILES[@]}
    

    Ok that doesn't recursively count files but I wanted to show the simple option first. A common use case might be for creating rollover backups of a file. This will create logfile.1, logfile.2, logfile.3 etc.

    CNT=(./logfile*); mv logfile logfile.${#CNT[@]}
    

    Recursive count with bash 4+ globstar enabled (as mentioned by @tripleee)

    FILES=(**/*); echo ${#FILES[@]}
    

    To get the count of files recursively we can still use find in the same way.

    FILES=(`find . -type f`); echo ${#FILES[@]}
    

提交回复
热议问题