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.

5
  • What's wrong with "${var/$pattern/}"? Can you clarify with some example inputs. Commented Nov 4, 2014 at 15:04
  • @anubhava He's looking for a fully anchored replacement. That finds a match anywhere. Commented Nov 4, 2014 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. Commented Nov 4, 2014 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. Commented Nov 4, 2014 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. Commented Nov 4, 2014 at 15:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.