Recursively counting files in a Linux directory

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

    This will work completely fine. Simple short. If you want to count the number of files present in a folder.

    ls | wc -l
    
    0 讨论(0)
  • 2020-11-28 17:35

    There are many correct answers here. Here's another!

    find . -type f | sort | uniq -w 10 -c
    

    where . is the folder to look in and 10 is the number of characters by which to group the directory.

    0 讨论(0)
  • 2020-11-28 17:39

    If you want a breakdown of how many files are in each dir under your current dir:

    for i in */ .*/ ; do 
        echo -n $i": " ; 
        (find "$i" -type f | wc -l) ; 
    done
    

    That can go all on one line, of course. The parenthesis clarify whose output wc -l is supposed to be watching (find $i -type f in this case).

    0 讨论(0)
  • 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 
    
    0 讨论(0)
  • 2020-11-28 17:41
    ls -l | grep -e -x -e -dr | wc -l 
    
    1. long list
    2. filter files and dirs
    3. count the filtered line no
    0 讨论(0)
  • 2020-11-28 17:43

    For the current directory:

    find -type f | wc -l
    
    0 讨论(0)
提交回复
热议问题