简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM