linux - 在 shell 脚本中从另一个字符串中剪切并删除一个字符串

标签 linux bash shell unix

我在 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/

相关文章:

c - fork() 并在 Linux 中杀死

bash - grep -vf 大文件太慢

python - 为什么在使用 subprocess.Popen 时出现 FileNotFoundError?

linux - 用于检查 PDF 是否被 ocr 的 BASH 脚本

linux - 对 Shell 脚本的一些疑问。

linux - nasm 可以生成二进制文件的调试符号吗?

c++ - 为什么语言环境 es_MX 有效但 es 无效?

linux - 使用物理地址获取内存的哪种实现是正确的?

shell - posix shell 脚本 : recursively remove all files starting with a certain prefix

linux - 查找和排序目录