1

In my script, have a possible version number: 15.03.2 set to variable $STRING. These numbers always change. I want to strip it down to: 15.03 (or whatever it will be next time).

How do I remove everything after the second . using sed?

Something like:

$(echo "$STRING" | sed "s/\.^$\.//")

(I don't know what ^, $ and others do, but they look related, so I just guessed.)

2

3 Answers 3

5

I think the better tool here is cut

echo '15.03.2' | cut -d . -f -2 
Sign up to request clarification or add additional context in comments.

2 Comments

Yes it is... :-).
Yes, a better tool and thanks. But, my question was about sed specifically, just sayin.
1

This might work for you (GNU sed):

sed 's/\.[^.]*//2g' file 

Remove the second or more occurrence of a period followed by zero or non-period character(s).

4 Comments

@EdMorton see here for details of why the flags number and g in the substitution command act as they do for GNU sed.
I'm very familiar with those flags, I just don't understand why that particular combination is necessary given that regexp. For example, given input of a.b.c.d and the regexp \.[^.]* the 2nd . is between b and c so the 2 should match the leftmost longest matching substring which is .c.d so why then do you also need a g after it?
@EdMorton using your example the 2nd matches .c the g flag then matches any following such regexs, in your case .d too. So the combination of number and g flag, matches from number to the end of the string.
Ah, right, I was getting confused about what the [^.]* would match, thanks.
1
$ echo '15.03.2' | sed 's/\([^.]*\.[^.]*\)\..*/\1/' 15.03 

More generally to skip N periods:

$ echo '15.03.2.3.4.5' | sed -E 's/(([^.]*\.){2}[^.]*)\..*/\1/' 15.03.2 $ echo '15.03.2.3.4.5' | sed -E 's/(([^.]*\.){3}[^.]*)\..*/\1/' 15.03.2.3 $ echo '15.03.2.3.4.5' | sed -E 's/(([^.]*\.){4}[^.]*)\..*/\1/' 15.03.2.3.4 

1 Comment

thanks for this, it's useful and you will be remembered.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.