I'm using this script to save the number of files in a main folder, but it also counts the subfolders inside that main folder.
nfiles=$(ls -1 /home/userA/mainfolder | wc -l)
Any advice how I can modify it to only include files not folders?

- 829,060

- 529
2 Answers
Don't use find
for this.
Besides requiring non-portable GNU extensions to make it work, it also has to stat()
every file for which it searches. ls
, on the other hand, can simply list the current directory's dentries out -1
per line while -q
uoting all non-printables with a ? question mark (to include \n
ewlines), and appending a /
for each directory listing.
That way for a simple -c
ount of non-dotfiles in the current directory you can just do:
ls -1pq | grep -c -v /
And the entire process is not only likely faster than find
would be, it is also POSIXly done.

- 58,310
Rather than parsing ls
, you can use find
:
find . -maxdepth 1 -type f ! -name ".*" | wc -l
This will find all files (-type f
) in the current directory (.
) except those beginning with a . (! -name ".*"
) and pass the result to wc
to count the lines.
To use it as a variable in your script:
nfiles=$(find . -maxdepth 1 -type f ! -name ".*" | wc -l)

- 242,166

- 73,126
-
1
-
How, exactly, is this superior to "parsing
ls
"? One of the big issues with parsing the output fromls
is that filenames can contain newlines. Well, won'tfind … -print | wc -l
fail in exactly the same way asls | wc -l
? Hint: see this and this. – G-Man Says 'Reinstate Monica' May 06 '15 at 03:53
find . -maxdepth 1 -type f | wc -l
(don't parsels
)... – jasonwryan Mar 16 '15 at 02:50nfiles= find /home/userA/mainfolder -maxdepth 1 -type f | wc -l
but it saysbash: /home/userA/mainfolder: is a directory 0
– Tak Mar 16 '15 at 02:55nfiles=$(find . -maxdepth 1 -type f | wc -l) && echo "$nfiles"
– jasonwryan Mar 16 '15 at 03:25