Mike Mike - 9 months ago 26
Bash Question

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
. Whats wrong here?


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