如何匹配,直到字符的bash shell中最后一次出现 [英] How to match until the last occurrence of a character in bash shell
问题描述
我使用卷曲
和剪切
像下方的输出。
I am using curl
and cut
on a output like below.
var=$(curl https://avc.com/actuator/info | tr '"' '\n' | grep - | head -n1 | cut -d'-' -f -1, -3)
Varible VAR
获得有两种类型的值(一次)。
Varible var
gets have two kinds of values (one at a time).
HIX_MAIN-7ae526629f6939f717165c526dad3b7f0819d85b
HIX-R1-1-3b5126629f67892110165c524gbc5d5g1808c9b5
我其实想获得的一切,直到最后 - 。即 HIX-MAIN
或 HIX-R1-1
。
显示的命令工作正常,要获得 HIX-R1-1
。
The command shown works fine to get HIX-R1-1
.
不过,我想这是错误的方式,当我有一些类似的东西只有1 做的事 -
中的变量;它让我整个变量值(例如 HIX_MAIN-7ae526629f6939f717165c526dad3b7f0819d85b
)。
But I figured this is the wrong way to do when I have something something like only 1 -
in the variable; it is getting me the entire variable value (e.g. HIX_MAIN-7ae526629f6939f717165c526dad3b7f0819d85b
).
我如何去获得一切到最后' - '?到变量 VAR
How do I go about getting everything up to the last '-' into the variable var
?
推荐答案
这从上消除一切 -
来结束:
This removes everything from the last -
to the end:
sed 's/\(.*\)-.*/\1/'
作为例子:
$ echo HIX_MAIN-7ae52 | sed 's/\(.*\)-.*/\1/'
HIX_MAIN
$ echo HIX-R1-1-3b5126629f67 | sed 's/\(.*\)-.*/\1/'
HIX-R1-1
工作原理
sed的替换命令的形式 S /老/新/
,其中老
是一个普通的前pression。在这种情况下,正则表达式是 \\(* \\) - *
。这工作,因为 \\ -
是贪婪(* \\):它会匹配一切到最后 -
。由于逃脱括号中, \\(... \\)
,一切前的最后 -
将被保存在组1,我们可以称之为 \\ 1
。 。最后的 *
匹配一切后,最后的 -
。因此,只要行包含 -
,此正则表达式的整条生产线相匹配和替换命令替换整条生产线\\ 1
。
How it works
The sed substitute command has the form s/old/new/
where old
is a regular expression. In this case, the regex is \(.*\)-.*
. This works because \(.*\)-
is greedy: it will match everything up to the last -
. Because of the escaped parens,\(...\)
, everything before the last -
will be saved in group 1 which we can refer to as \1
. The final .*
matches everything after the last -
. Thus, as long as the line contains a -
, this regex matches the whole line and the substitute command replaces the whole line with \1
.
这篇关于如何匹配,直到字符的bash shell中最后一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!