MagicSea
MagicSea

Reputation: 13

match leading dots in bash if using regex

Say I want to match the leading dot in a string ".a"

So I type

[[ ".a" =~ ^\. ]] && echo "ha"

ha

[[ "a" =~ ^\. ]] && echo "ha"

ha

Why am I getting the same result here?

Upvotes: 1

Views: 935

Answers (3)

pynexj
pynexj

Reputation: 20798

There's some compatibility issues with =~ between Bash versions after 3.0. The safest way to use =~ in Bash is to put the RE pattern in a var:

$ pat='^\.foo'
$ [[ .foo =~ $pat ]] && echo yes || echo no
yes
$ [[ foo =~ $pat ]] && echo yes || echo no
no
$

For more details, see E14 on the Bash FAQ page.

Upvotes: 1

jim mcnamara
jim mcnamara

Reputation: 16399

You need to escape the dot it has meaning beyond just a period - it is a metacharacter in regex.

 [[ "a" =~ ^\. ]] && echo "ha"

Make the change in the other example as well.

Check your bash version - you need 4.0 or higher I believe.

Upvotes: 1

anishsane
anishsane

Reputation: 20980

Probably it's because bash tries to treat "." as a \ character, like \n \r etc.

In order to tell \ & . as 2 separate characters, try

[[ "a" =~ ^\\. ]] && echo ha

Upvotes: 0

Related Questions