Get the file count in a folder

What is the best way to get the file count (Including the subdirectories) under a folder?

One way would be..

find . -type f |wc -l

Hi un1xl0ver_rwx,

Another way could be:

ls -lR | awk '$7~/:/ && $1!~/^d/{print}' | wc -l

But the outputs are different between:

find . -type f | wc -l

and

ls -lR | awk '$7~/:/ && $1!~/^d/{print}' | wc -l

I compare and I found that when I use

"find . -type f

appear extra lines with

Some/Path/.exists

in empty folders and this count like another file when really doesn't exist.

Why does this happen?

Regards

1 Like

@cgkmal, why would you want to count files using ls -lR? your pattern "$1!~/^d/{print}" will also count other types such as sockets, pipes etc....

find Commands|wc -l

is what I needed.

Thanks!

Hi Kurumi,

In order to learn, may you show how it looks a socket, pipe and other different elements in a ls -lR print?

Regarding to your question:
Well, when I see the print of ls -lR, prints all files in a folder and its subfolders showing this structure:

./Some folder:
total 20
drwxr-xr-x 8 user user  4096 2011-03-17 20:13 Xlib
-rw-r--r-- 1  user user   948 2005-09-30 12:57 Changes

As far as I know, in this print out format, lines beginning with "d" are representing directories and the other would be files.
Being newbie in unix I don't know completely how it work linux systems, what you say is new for me, and I'll take present, thanks for that.

But actually using my code (in my case), the result (205 files) is less than find command's output (220).

I see is because "find . -type f" is adding "some path/.exists" lines like ls -lRa does.

Maybe somebody knows?

Regards.

Use this command this is the fastest , even faster than find.

 ls -lR . | egrep -c '^-'

The reason for difference is output in find and ls is ignoring hidden files.

2 Likes

Thanks dinjo_jo,

This gives me the same output as my original code.

I was thinking in something like that could explain, but I wasn't sure:p

Regards

you can make a pipe for example like this

mkfifo fifo_pipe

try it and do a ls -l and see what letter it holds

Both works great.
I wanted to include directories and hidden files as well.
So find works best for me.

find .|grep "^./"|wc -l
ls -lR . | grep ^[-d]|wc -l

Hi kurumi,

Thanks! I've tested and know I see that printed lines could begin with "p" too, and some other symbols as "-".

With "man ls" I can see the options of the "ls" command but not the print out description and all its options.

Do you know where can I see that?

Thanks again

ls -lRa show all and

ls -lRa | awk '$0~/^-/{print}' | wc -l

Gives me now the same output as "find . type f" shows:D

Regards

@cgkmal, there are more information from coreutils info.

info coreutils 'ls invocation'
1 Like

Many thanks kurumi, I have it now!.:b: