Reputation: 37394
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
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=""
.
$ 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