Bash:从字符串中删除字符直到某个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40506782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:22:38  来源:igfitidea点击:

Bash: Delete characters until a certain character from String

stringbashshellsedcut

提问by Anne K.

how can I delete characters from a String until a certain character with bash? Example:

如何使用 bash 从字符串中删除字符直到某个字符?例子:

"ananas1kiwi2apple1banana2tree"

shall look like this:

看起来像这样:

"apple1banana2tree"

Thank you!

谢谢!

回答by heemayl

If you want to remove the substring upto 2, using bashparameter expansion:

如果要删除子字符串 upto 2,请使用bash参数扩展:

${var#*2}
  • #does non-greedy match from left, use ##for greediness

  • #*2matches and discards upto first 2from variable var

  • #从左侧进行非贪婪匹配,##用于贪婪

  • #*2匹配并丢弃2从变量到第一个var

Example:

例子:

$ var='ananas1kiwi2apple1banana2tree'
$ echo "${var#*2}"
apple1banana2tree

回答by Inian

Using pure bashshell parameter expansion.

使用纯bashshell 参数扩展

$ string="ananas1kiwi2apple1banana2tree"
$ newString="${string#*2}"
$ printf "%s\n" "$newString"
apple1banana2tree