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

Viewed 177

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.

2 Answers

Like this:

[STEP 101] $ v=abc.svc.svc.cluster.local
[STEP 102] $ echo ${v%.svc*}
abc.svc
[STEP 103] $ v=abc.svc.cluster.local
[STEP 104] $ echo ${v%.svc*}
abc
[STEP 105] $

And, use %% for the greedy behavior:

[STEP 105] $ v=abc.svc.svc.cluster.local
[STEP 106] $ echo ${v%%.svc*}
abc
[STEP 107] $

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. [...]

Use rename utility like so:

rename --dry-run 's{(.*)[.]svc.*}{$1}' *

When satisfied with the planned changes, remove --dry-run:

rename 's{(.*)[.]svc.*}{$1}' *

The command-line utility rename comes in many flavors. Most of them should work for this task. I used the rename version 1.601 by Aristotle Pagaltzis. To install rename, simply download its Perl script and place it into $PATH. Or install rename using conda, like so:

conda install rename
Related