如何在bash中只获取字符串的一部分而没有结尾

How to get only one part of the string without the end in bash

我只想获取字符串 new-profile-input 的一部分,我需要的部分是:没有“-input”的“new-profile”。

我这样试过:

cat automatization_test.sh |  grep -oh "\new-profile-input\w*" | grep -o "\-input\w*"

但是,我得到输出:

-输入

但是,我需要字符串的第一部分而不是最后一部分。请注意,“new-profile”总是会改变,所以这就是为什么我必须专注于删除“-input”而不是只获取“new-profile”。

提前谢谢你,

如果支持,您可以将 -P 用于与 Perl 兼容的正则表达式,匹配整行并使用正向先行断言最后一次出现的 - 到右侧。

注意,除了使用 cat,您还可以在 grep 命令的末尾添加文件。

grep -oP '.+(?=-)' automatization_test.sh

输出

new-profile

查看匹配项 regex demo


对于更具体的匹配,您可以使用正向先行断言 -input 到右侧并匹配非空白字符。

grep -oP '(?<!\S)\S+(?=-input(?!\S))' automatization_test.sh

查看匹配项 regex demo

使用 sed,您可以排除最后一个 - 斜线后的所有内容,其中 -input 将在您的示例字符串中。

$ sed 's/\(.*\)-.*//' automatization_test.sh
new-profile