提取点前的子字符串

Extract substring before dot

我尝试减去 bash 中 dot (.) 之前的第一个字符串。

例如:

1.2.3 -> 1
11.4.1 -> 11

我基于docs使用了以下命令:

s=4.5.0
echo "${s%.*}"

但它输出 4.5 而不是 4。我不明白。

这是为什么?

您需要使用 %% 从末尾删除 最长的 匹配项:

$ echo "${s%%.*}"
4

来自the docs

${parameter%%word}
Remove Largest Suffix Pattern. The word shall be expanded to produce a pattern. The parameter expansion shall then result in parameter, with the largest portion of the suffix matched by the pattern deleted.

您还可以使用 shell(自 bash 3.0 起)的最新版本中内置的 bash Regular Expressions 功能,使用代字号(=~) 运算符。

$ string="s=4.5.0"
$ [[ $string =~ =([[:alnum:]]+).(.*) ]] && printf "%s\n" "${BASH_REMATCH[1]}"
4
$ string="s=32.5.0"
$ [[ $string =~ =([[:alnum:]]+).(.*) ]] && printf "%s\n" "${BASH_REMATCH[1]}"
32