Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove non-greedy suffix from string in bash?

I would like to remove any suffix from a string starting with the last .svc. . As a example:

abc.svc.cluster.local => abc

abc.svc.svc.cluster.local => abc.svc

abc.txt => abc.txt

abc.svc.xyz.svc.zzz => abc.svc.xyz

svc.xxx => svc.xxx (missing . before svc)

If I was doing this is Go, I would find the last index of substring .svc. and then trim from that index.

How do I do this in bash? Thanks.

like image 709
codefx Avatar asked Nov 16 '25 22:11

codefx


1 Answers

Like this:

$ v=abc.svc.svc.cluster.local
$ echo ${v%.svc*}
abc.svc
$ v=abc.svc.cluster.local
$ echo ${v%.svc*}
abc

And, use %% for the greedy behavior:

$ v=abc.svc.svc.cluster.local
$ echo ${v%%.svc*}
abc

According to man bash:

  • ${parameter%word}
    ${parameter%%word}

    The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the % case) or the longest matching pattern (the %% case) deleted. [...]

like image 128
pynexj Avatar answered Nov 18 '25 11:11

pynexj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!