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
This will work completely fine. Simple short. If you want to count the number of files present in a folder.
ls | wc -l
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.
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).
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
ls -l | grep -e -x -e -dr | wc -l
For the current directory:
find -type f | wc -l