How to count the number of files starting with a pattern in a Directory

Hi!

In our current directory there are around 35000 files.

Out of these a few thousands(around 20000) start with, "testfiles9842323879838".

I want to count the number of files that have filenames starting with the above pattern. Please help me with the command i could use.

Thank you!!!

ls testfiles9842323879838* | wc -l

Actually i forgot to mention but i already tried this... :slight_smile: and it gave the following error:

"Argument list too long".

Can you help me with this ? Thanks so much for you reply!

Try this then:

ls | awk '/^testfiles9842323879838/{c++};END{print c}'
1 Like

Hi,
You could try find command. I suppose it will work faster than ls and also the issue due to huge no. of files to be tried should disappear.

find . -name "testfiles9842323879838*" | wc -l

In case you are sure all the files are located directly under one directory, you could also use maxdepth with find. This would prevent find cmd from recursively searching all the subdirectories located underneath the directory in focus.

find . -maxdepth 1 -name "testfiles9842323879838*" | wc -l

Wow!!!! It worked! You are a genuis Sir. Thanks so much.

Now, if i want to list the same files into a Txt file, can i have the command to do that? We need to have the list of all these files(20000) into a txt file or some file.
Forgive me if i am using the same post to ask a different/related question.
God bless!

---------- Post updated at 03:18 PM ---------- Previous update was at 03:13 PM ----------

Pranab/ thanks for your help too :slight_smile:

Try:

ls | awk '/^testfiles9842323879838/' > file.txt

Thanks again Sir! God bless this forum and wonderful people like you who have the passion to share knowledge!

It worked!!

Thanks so much!