bash - 字符串操作,可选字符

标签 bash

使用 grep,您可以使用问号 ? 来表示可选字符,即要匹配 0 次或 1 次的字符。

$ foo=qwerasdf

$ grep -Eo fx? <<< $foo
f

问题是 Bash String Manipulation 是否具有类似的功能?有点像

$ echo ${foo%fx?}

最佳答案

您可能在谈论 parameter expansion .它使用 shell 模式,而不是正则表达式,所以答案是否定的

进一步阅读后,我注意到如果你

shopt -s extglob

你可以使用extended pattern matching它可以实现类似于正则表达式的功能,尽管语法略有不同。

检查一下:

word="mre"
# this returns true
if [[ $word == m?(o)re ]]; then echo true; else echo false; fi

word="more"
# this also returns true
if [[ $word == m?(o)re ]]; then echo true; else echo false; fi

word="mooooooooooore"
# again, true
if [[ $word == m+(o)re ]]; then echo true; else echo false; fi

也适用于参数扩展,

word="noooooooooooo"
# outputs 'nay'
echo ${word/+(o)/ay}
# outputs 'nayooooooooooo'
echo ${word/o/ay}

关于bash - 字符串操作,可选字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12971309/

相关文章:

linux - 在 bash 中循环每个变量一次,而不是在第二个循环中每隔一个变量循环一次?

bash:使用 set -e 运行脚本(errexit)

linux - 为什么 mplayer 在循环时退出 Bash?

bash - UNIX 统计时间格式

regex - 在终端中选择带有前导 "_"(下划线)符号的文件夹(不是文件)

linux - 在 Linux 中删除以特定字符串结尾的特定文件

bash - 以给定的行数从 file1 到 file2 交错文本文件

bash - 使用 curl 循环访问 url 的 Shell 脚本

linux - 如何用 bash 脚本匹配 "whitespace"和 "OR"条件?

linux - 如何检查程序是否在 Windows 上的 Ubuntu 上的 Bash 中运行,而不仅仅是普通的 Ubuntu?