Sed version extract

Viewed 109

I am trying to extract the version number from a string. I am unable to find the exact regex to find what I need.

For eg -

1012-EPS-Test-OF-Something-1.3 

I need sed to only extract 1.3 from the above line.

I have tried quite a few things until now something like but it is clearly not working out

sed 's/[^0-9.0-9]*//')
4 Answers

With your shown samples, easiest way could be. Simply print value of shell variable into awk program as input and then setting field separator as - and printing the last field value in it.

echo "$string" | awk -F'-' '{print $NF}'

2nd solution: In case you could have anything else also apart from version number in last field of your value(where - is field delimiter) then use match function of awk.

echo "$var" | 
awk -F'-' 'match($NF,/[0-9]+(\.[0-9]+)*/){print substr($NF,RSTART,RLENGTH)}'

3rd solution: Using GNU grep try following once. Using \K option for GNU grep here. This will match everything till - and then mentioning \K will forget OR wouldn't consider that matched value for printing and will print all further matched value(with further mentioned regex).

echo "$var" | grep -oP '.*-\K\d+(\.\d+)*'

This should work in any grep:

s='1012-EPS-Test-OF-Something-1.3'
grep -Eo '[0-9]+(\.[0-9]+)+' <<< "$s"

1.3

This might work for you (GNU sed):

sed -n 's/.*[^0-9.]//p' file

The regexp is greedy and swallows the whole line .* then steps back a character at a time till the first match of [^0-9.], removes the front portion and prints the remainder.

You can use string manipulation to get the last part after -:

s='1012-EPS-Test-OF-Something-1.3'
s="${s##*-}"

See this online demo:

#!/bin/bash
s='1012-EPS-Test-OF-Something-1.3'
s="${s##*-}"
echo "$s"
# => 1.3

See 10.1. Manipulating Strings:

${string##substring}

    Deletes longest match of $substring from front of $string.

Related