Recursively counting files in a Linux directory

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

    If you want to avoid error cases, don't allow wc -l to see files with newlines (which it will count as 2+ files)

    e.g. Consider a case where we have a single file with a single EOL character in it

    > mkdir emptydir && cd emptydir
    > touch $'file with EOL(\n) character in it'
    > find -type f
    ./file with EOL(?) character in it
    > find -type f | wc -l
    2
    

    Since at least gnu wc does not appear to have an option to read/count a null terminated list (except from a file), the easiest solution would just be to not pass it filenames, but a static output each time a file is found, e.g. in the same directory as above

    > find -type f -exec printf '\n' \; | wc -l
    1
    

    Or if your find supports it

    > find -type f -printf '\n' | wc -l
    1 
    

提交回复
热议问题