1

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
James Brown
  • 36,089
  • 7
  • 43
  • 59
  • What's wrong with `"${var/$pattern/}"`? Can you clarify with some example inputs. – anubhava Nov 04 '14 at 15:04
  • @anubhava He's looking for a fully anchored replacement. That finds a match anywhere. – Etan Reisner Nov 04 '14 at 15:05
  • 1
    I can't think of anything materially better than that `if` statement. `[ "$var" = ABCD ] && var=""` is slightly more terse but the same idea. – Etan Reisner Nov 04 '14 at 15:06
  • @etan and @ fedorgui it works for me. Out of curiosity I'm going to leave this open for a while to see if there are other solutions. Thanks guys. – James Brown Nov 04 '14 at 15:14
  • 1
    Note that your first two examples do NOT modify `$var` -- they expand to a string that comes from `$var` and has the corresponding change, but `$var` itself remains unchanged -- later instances of `$var` will not be affected. – Chris Dodd Nov 04 '14 at 15:33

1 Answers1

5

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.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598