如何在bash中打印特定单词之前的字符串?



我想学习如何从这个特定的输出中只提取内核版本:

3.10.0-1127.18.2.el7.x86_64Repository rhel-7-server-optional-rpms is listed more than once in the configuration

这是我想要的输出:3.10.0-1127.18.2.el7.x86_64

bash:

var="3.10.0-1127.18.2.el7.x86_64Repository rhel-7-server-optional-rpms"
echo "${var%%Repository*}"

请参见手册中的3.5.3 Shell参数展开。

有几种方法。
A "simple"正在使用sed和正则表达式来替换要剥离的部分。
,

echo "3.10.0-1127.18.2.el7.x86_64Repository rhel-7-server-optional-rpms" | sed -E "s/Repository.*//"
3.10.0-1127.18.2.el7.x86_64

说明sed命令的用法:sed -E "s/Repository.*//":

E '表示扩展正则表达式。
和sed语法替换为:

s/regexp/replacement/

尝试将regexp与模式空间匹配。如果成功,将匹配的部分替换为replacement

这里我们用nothing替换找到的字符串

最新更新