So far I have this:
find -name ".txt"
find . -name '*.txt' | wc -l
-l option to
wc tells it to return just the number of lines.
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.
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