[英]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=""
。
$ 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.