2

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

2 Answers2

8

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
John1024
  • 109,961
  • 14
  • 137
  • 171
0
find -type f -name "*.h" -mtime +10 -print | wc -l

This worked out.

  • 1
    I don't understand how this answers the question, since you wanted to find txt files, not .h files. Second, it'd be more helpful if you explained what your code is doing and why it worked. Finally, why post this answer after accepting the other answer? – m13op22 Apr 23 '19 at 13:57