bash - 从 bash 中的字符串中删除指定的字符串模式

标签 bash glob

我找到了一个不错的answer这解释了如何从字符串变量中删除指定的模式。在本例中,要删除“foo”,我们使用以下命令:

string="fooSTUFF"
string="${string#foo}"

但是,我想添加“OR”功能,当我的字符串以其中任何一个开头时,该功能将能够删除“foo”或“boo”,并保留字符串原样(如果确实如此)不以“foo”或“boo”开头。因此,修改后的脚本应该如下所示:

string="fooSTUFF"
string="${string#(foo OR boo)}"

如何正确实现?

最佳答案

如果您已设置 extglob(扩展 glob)shell 选项

shopt -s extglob

然后你可以写:

string="${string#@(foo|boo)}"

扩展模式记录在 bash manual 中;它们采用以下形式:

  • ?(pattern-list):匹配零次或一次出现的给定模式。

  • *(pattern-list):匹配零次或多次出现的给定模式。

  • +(pattern-list):匹配给定模式的一次或多次出现。

  • @(pattern-list):匹配给定模式之一。

  • !(pattern-list):匹配除给定模式之一之外的任何内容。

在所有情况下,pattern-list 都是由 | 分隔的模式列表

关于bash - 从 bash 中的字符串中删除指定的字符串模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42277361/

相关文章:

node.js - npm postinstall 使用多个命令失败

Linux bash 命令错误地处理输出中的零。

linux - Ldapsearch 使用不显示数据的变量进行过滤

bash:如何删除最后一个符号

python - 正则表达式、glob、Python

ruby - 如何让 Rake 使用 RVM 的 Ruby?

Python - 根据儒略日增量重命名文件

Python 如何搜索带有特殊符号的子字符串?和 *(类似正则表达式)

括号目录中的 PHP glob()

linux - Linux 终端中的文件 Glob 模式