Search code examples
linuxfindwc

How do I find the number of all .txt files in a directory and all sub directories using specifically the find command and the wc command?


So far I have this:

find -name ".txt"

I'm not quite sure how to use wc to find out the exact number of files. When using the command above, all the .txt files show up, but I need the exact number of files with the .txt extension. Please don't suggest using other commands as I'd like to specifically use find and wc. Thanks


Solution

  • Try:

    find . -name '*.txt' | wc -l
    

    The -l option to wc tells it to return just the number of lines.

    Improvement (requires GNU find)

    The above will give the wrong number if any .txt file name contains a newline character. This will work correctly with any file names:

    find . -iname '*.txt' -printf '1\n' | wc -l
    

    -printf '1\n tells find to print just the line 1 for each file name found. This avoids problems with file names having difficult characters.

    Example

    Let's create two .txt files, one with a newline in its name:

    $ touch dir1/dir2/a.txt $'dir1/dir2/b\nc.txt'
    

    Now, let's find the find command:

    $ find . -name '*.txt'
    ./dir1/dir2/b?c.txt
    ./dir1/dir2/a.txt
    

    To count the files:

    $ find . -name '*.txt' | wc -l
    3
    

    As you can see, the answer is off by one. The improved version, however, works correctly:

    $ find . -iname '*.txt' -printf '1\n' | wc -l
    2