简体   繁体   English

打击和替换整个字符串变量?

[英]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. 我正在尝试使用Bash替换来替换变量中的整个字符串(如果它与模式匹配)。 For example: 例如:

pattern="ABCD"

${var/pattern/}

removes (replaces with nothing) the first occurrence of $pattern in $var 删除(无替换) $var第一次出现的$pattern

${var#pattern}

removes $pattern in the beginning of $var $var开头删除$pattern

But how can I remove regex pattern "^ABCD$" from $var ? 但是如何从$var删除正则表达式模式"^ABCD$" 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 . 它使用$pattern定义的正则表达式检查$var In case it matches, it performs the command var="" . 如果匹配,则执行命令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. 有关更多信息,请参见在BASH Shell脚本中检查字符串是否与正则表达式匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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