mnabil
mnabil

Reputation: 745

Find if a string starts with a specific pattern using regex in bash script

I'm trying to use regext to detect if a string starts with a specific pattern or not but it does not work with me:

   #!/bin/bash
   line="{{ - hello dear - }}"
   if [[ "${line}" =~ ^\{\{\s*-\s*hello\s*.*\}\} ]]; then
        echo "got it "
   fi

In this example, I expect the if condition to detect that the line variable has a string that starts with "{{ - hello" and ends with "}}" However, it does not do so as the echo message is not printed!

Upvotes: 1

Views: 609

Answers (2)

anubhava
anubhava

Reputation: 786021

There is no real need to use regex here. You can just use glob matching in bash like this:

line="{{ - hello dear - }}"

[[ $line == '{{ - hello'*'}}' ]] && echo "got it "

got it

Upvotes: 1

konsolebox
konsolebox

Reputation: 75588

You can store the regex in a variable to make it work. It was a workaround in 3.2. Not sure why it's needed again in newer versions.

#!/bin/bash

line="{{ - hello dear - }}"
regex='^\{\{\s*-\s*hello\s*.*\}\}'

if [[ "${line}" =~ $regex ]]; then
     echo "got it "
fi

Also consider using extended pattern matching with == instead. I believe it has a weaker "engine" but it's more readable sometimes.

shopt -s extglob
...
[[ $line == "{{ - hello dear - }}"* ]] && echo "Got it."

(Actually that's not even an extended pattern yet.)

Upvotes: 2

Related Questions