在 bash 个脚本中捕获 case 语句中的模式组

Capture pattern group in case statements in bash scripts

bash 中的典型 case 语句可能是:

k=abcdef
case $k in
    "abc"* )
        echo "pattern found"
        ;;
esac

我的一个变量具有模式 key=value,我希望从中提取值。

k="abc=value1"
case $k in
    "abc="* )
        echo "key abc found";
        # extract "value1"
        ;;
esac

如何从键中提取值?喜欢 key1=(.*) 并通过说 </code> 或 <code>.

获取捕获的组

您可以将子字符串与您拥有的正则表达式匹配,并使用 ${BASH_REMATCH[1]}:

访问第 1 组
k="abc=value1"
rx='abc=(.*)'
if [[ $k =~ $rx ]]; then
    echo ${BASH_REMATCH[1]};
fi
# => value1

online demo

请注意,通过在单独的变量中声明它来使用正则表达式是最直接的方法,这样代码在支持 =~ 匹配的所有 Bash 版本中都能按预期工作操作员。以 Bash 3.2[[ $k =~ "abc=(.*)" ]] 开头的代码将触发文字字符串比较而不是正则表达式比较:

f. Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

如果你有一个复杂的场景,正则表达式是有意义的。在你的情况下,string manipulations like 也可以工作:

k="abc=value1"
echo ${k#*=}
# => value1

参见 another demo online。在这里,# 触发删除字符串开头和第一个 = 字符(包括它)之间的最短子字符串的子字符串。请参阅文档:

Substring Removal

${string#substring}

        Deletes shortest match of $substring from front of $string.