4

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?

Tak
  • 529

2 Answers2

3

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 -quoting all non-printables with a ? question mark (to include \newlines), and appending a / for each directory listing.

That way for a simple -count 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.

mikeserv
  • 58,310
2

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)
terdon
  • 242,166
jasonwryan
  • 73,126