bash 提取点前的子串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40738346/
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
Extract substring before dot
提问by Mornor
I try to substract the first string before a dot
(.
) in bash.
我尝试在 bash 中减去dot
( .
)之前的第一个字符串。
For instance:
例如:
1.2.3 -> 1
11.4.1 -> 11
I used the following command based on the docs:
我根据文档使用了以下命令:
s=4.5.0
echo "${s%.*}"
But it ouptuts 4.5
instead of 4
. I don't get it.
但它输出4.5
而不是4
. 我不明白。
Why is that?
这是为什么?
回答by Tom Fenech
You need to use %%
to remove the longestmatch from the end:
您需要使用从末尾%%
删除最长的匹配:
$ echo "${s%%.*}"
4
From the docs:
从文档:
${parameter%%word}
Remove Largest Suffix Pattern. The wordshall 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.
${parameter%%word}
删除最大后缀模式。这个词应该被扩展以产生一个模式。然后参数扩展将导致参数,与删除模式匹配的后缀的最大部分。
回答by Inian
You can also use the bash
Regular Expressionsfeature built-in in the recent versions of the shell (since bash 3.0
), using the tilde(=~
) operator.
您还可以使用tilde( ) 运算符,使用内置于最新版本的 shell(自)中的bash
正则表达式功能。bash 3.0
=~
$ 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