Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count files in a directory with filename matching a string

The command:

ls /some/path/some/dir/ | grep some_mask_*.txt | wc -l

returns the correct number of files when doing this via ssh on bash. When I put this into a .sh Script

iFiles=`ls /some/path/some/dir/ | grep some_mask_*.txt | wc -l`
echo "iFiles: ${iFiles}"

it is always 0. Whats wrong here?

Solution:
When I worked on it I found out that my "wildcard-mask" seems to be the problem. using grep some_mask_ | grep \.txt instead of the single grep above helped me to solve the problem for the first.

I marked the answer as solution which pretty much describes exactly what I made wrong. I'm going to edit my script now. Thanks everyone.

like image 335
Yaerox Avatar asked Nov 29 '22 23:11

Yaerox


1 Answers

The problem here is that grep some_mask_*.txt is expanded by the shell and not by grep, so most likely you have a file in the directory where grep is executed which matches some_mask_*.txtand that filename is then used by grep as a filter.

If you want to ensure that the pattern is used by grep then you need to enclose it in single quotes. In addition you need to write the pattern as a regexp and not as a wildcard match (which bash uses for matching). Putting this together your command line version should be:

ls /some/path/some/dir/ | grep 'some_mask_.*\.txt' | wc -l

and the script:

iFiles=`ls /some/path/some/dir/ | grep 'some_mask_.*\.txt' | wc -l`
echo "iFiles: ${iFiles}"

Note that . needs to be prefixed with a backslash since it has special significance as a regexp that matches a single character.

I would also suggest that you postfix the regexp with $ in order to anchor it to the end (thus ensuring that the regexp matches filenames that ends with ".txt"):

ls /some/path/some/dir/ | grep 'some_mask_.*\.txt$' | wc -l
like image 61
Stefan Farestam Avatar answered Dec 04 '22 06:12

Stefan Farestam