sansSpoon
sansSpoon

Reputation: 2185

Regex operation to match a white-space not working

I'm trying to make a condition that matches any amount of spaces in a file name $f. But what I have seems to be matching everything?

if [[ $f =~ [[:space:]]* ]]; then
    echo found a space
fi

This matches i-have-no-spaces.jpg as well as i have spaces.jpg

Upvotes: 2

Views: 1530

Answers (1)

anubhava
anubhava

Reputation: 785166

Don't use *, it means 0 or more matches.

Use

if [[ $f =~ [[:space:]] ]]; then
    echo "found a space"
fi

However in BASH, I suggest to not to use regex for this, just use glob matching with =:

if [[ $f = *[[:space:]]* ]]; then
    echo "found a space"
fi

Upvotes: 2

Related Questions