Chris Hansen
Chris Hansen

Reputation: 8663

Counting filenames matching a regex in bash

I have the following script

setup=`ls ./test | egrep 'm-ha-.........js'`
regex="m-ha-(........)\.js"

if [[ "$setup" =~ $regex ]]
then
    checksum=${BASH_REMATCH[1]}
fi

I noticed that if [[ "$setup" =~ $regex ]] returns the first file that matches the regex in BATCH_REMATCH.

Is there a way to test how many files matches the regex? I want to return an error, if there are multiple files that matches the regex.

Upvotes: 1

Views: 97

Answers (1)

tripleee
tripleee

Reputation: 189477

You don't need a regex, or ls, for this.

matches=(./test/m-ha-????????.js)
[[ ${#matches[*]} -gt 1 ]] && echo "More than one."

We expand the wildcard into an array and examine the number of elements in the array.

If you want to strip the prefix, ${match[0]#mh-a-} returns the first element with the prefix removed. The % interpolation operator similarly strips a suffix, e.g. ${match[0]%.js}. You can't strip from both ends at the same time, but you can loop over the matches:

for match in "${matches[@]%.js}"; do
    echo "${match#./test/m-ha-}"
done

Notice that the array won't be empty if there are no matches unless you explicitly set the nullglob option.

Upvotes: 4

Related Questions