James Brown
James Brown

Reputation: 37394

Bash and replacing the whole string in variable?

I'm trying to use Bash replacement to replace the whole string in variable if it matches a pattern. For example:

pattern="ABCD"

${var/pattern/}

removes (replaces with nothing) the first occurrence of $pattern in $var

${var#pattern}

removes $pattern in the beginning of $var

But how can I remove regex pattern "^ABCD$" from $var? I could:

if [ $var == "ABCD" ] ; then 
  echo "This is a match." # or whatever replacement
fi

but that's quite what I'm looking for.

Upvotes: 1

Views: 493

Answers (1)

fedorqui
fedorqui

Reputation: 289495

You can do a regular expression check:

pattern="^ABCD$"
[[ "$var" =~ $pattern ]] && var=""

it checks $var with the regular expression defined in $pattern. In case it matches, it performs the command var="".

Test

$ pattern="^ABCD$"
$ var="ABCD"
$ [[ "$var" =~ $pattern ]] && echo "yes"
yes
$ var="1ABCD"
$ [[ "$var" =~ $pattern ]] && echo "yes"
$ 

See check if string match a regex in BASH Shell script for more info.

Upvotes: 5

Related Questions