我在 shell 脚本中有以下字符串。
var="rule:access=allow,default=default value,OTHER=0,SOMETHING=1"
我需要从 $var 中删除“default=default value”。 这样,最终的字符串就会变成这样:
var="rule:access=allow,OTHER=0,SOMETHING=1"
注意:默认后的值可以是任何东西。它可能是“默认=其他”。它不是固定的。我需要删除该文本。 如何才能做到这一点?
最佳答案
修改问题的答案
$ echo "$var" | sed 's/default=[^,]*,//'
rule:access=allow,OTHER=0,SOMETHING=1
如果我们想更新var
的值,我们使用命令替换:
$ var="$(echo "$var" | sed 's/default=[^,]*,//')"
$ echo "$var"
rule:access=allow,OTHER=0,SOMETHING=1
原始问题的答案
使用庆典
要删除 default=default value,
,请使用模式替换:
$ var="${var/default=default value,/}"
$ echo "$var"
rule:access=allow,OTHER=0,SOMETHING=1
此功能记录在 man bash
中:
${parameter/pattern/string}
Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is @ or *, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.
使用 sed
$ var="$(echo "$var" | sed 's/default=default value,//')"
$ echo "$var"
rule:access=allow,OTHER=0,SOMETHING=1
关于linux - 在 shell 脚本中从另一个字符串中剪切并删除一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37453395/