0

I'm trying to strip prefixes from a SemVer, i.e, making 1.2.3-prefix.42 into 1.2.3.

I'm using this RegEx found in https://github.com/mojombo/semver/issues/32#issuecomment-7663411:

^(\d+\.\d+\.\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?

When using Ruby's gsub method, it works:

puts '1.2.3-alpha.4'.gsub(/^(\d+\.\d+\.\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/, '\1')
# => 1.2.3

But when using sed form the terminal it doesn't:

$ echo '1.2.3-alpha.4' | sed -e 's/^(\d+\.\d+\.\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/\1/g'
$ 1.2.3-alpha.4

What am I missing?

I'm using zsh on Mac OS X.

Thanks

Eric Platon
  • 9,266
  • 6
  • 40
  • 47
mokagio
  • 14,681
  • 3
  • 45
  • 52
  • 2
    I believe non-capturing groups (`(?: ... )`) aren't available in sed. More info: http://stackoverflow.com/questions/4823864/how-do-you-specify-non-capturing-brackets-in-sed – Jordan Running Nov 25 '15 at 23:00
  • 1
    While capture groups are probably you're main problem, I'd be surprised if the stock install of `sed` in OSX supports `\d`, use `[0-9]` instead. Good luck. – shellter Nov 26 '15 at 01:07

2 Answers2

2

If you want to make strings like 1.2.3-prefix.42 become 1.2.3 you don't have to prepare such complicated sed expression.

Just check if the string starts with a combination of three numbers separated by dots and catch it. Then, print it back:

$ sed -r 's/^([0-9]\.[0-9]\.[0-9]).*/\1/' <<< "1.2.3-prefix.42"
1.2.3

Since the rest of the patterns you are using in the Ruby expression use ? we can assume they are optional, so I am not including them.

fedorqui
  • 252,262
  • 96
  • 511
  • 570
  • Thanks @fedorqui, but although correct, your answer doesn't work on OS X's stock `sed`. – mokagio Nov 28 '15 at 23:03
  • @mokagio that's weird! I don't have such version here, you may want to add the output to see what is missing to make it BSD compatible. – fedorqui Nov 29 '15 at 12:17
1

It sounds like you're more comfortable with ruby, you can use it like sed:

echo '1.2.3-prefix.42' | ruby.exe -ne 'puts $_.sub /[^\d.].+/, ""'
#=> 1.2.3

I don't think you really want to learn sed if you don't need to.

pguardiario
  • 51,516
  • 17
  • 106
  • 147
  • Thanks @pguardiario. After all "the easiest way to solve a problem is not to have it in the first place." – mokagio Nov 28 '15 at 23:06