Regex to match exact version phrase

I have versions like:

v1.0.3-preview2
v1.0.3-sometext
v1.0.3
v1.0.2
v1.0.1

I am trying to get the latest version that is not preview (doesn't have text after version number) , so result should be: v1.0.3

I used this grep: grep -m1 "[v\d+\.\d+.\d+$]"

but it still outputs: v1.0.3-preview2

what I could be missing here?


Solution 1:

To return first match for pattern v<num>.<num>.<num>, use:

grep -m1 -E '^v[0-9]+(\.[0-9]+){2}$' file

v1.0.3

If you input file is unsorted then use grep | sort -V | head as:

grep -E '^v[0-9]+(\.[0-9]+){2}$' f | sort -rV | head -1

When you use ^ or $ inside [...] they are treated a literal character not the anchors.

RegEx Details:

  • ^: Start
  • v: Match v
  • [0-9]+: Match 1+ digits
  • (\.[0-9]+){2}: Match a dot followed by 1+ dots. Repeat this group 2 times
  • $: End

Solution 2:

To match the digits with grep, you can use

grep -m1 "v[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+$" file

Note that you don't need the [ and ] in your pattern, and to escape the dot to match it literally.

Solution 3:

With awk you could try following awk code.

awk 'match($0,/^v[0-9]+(\.[0-9]+){2}$/){print;exit}' Input_file

Explanation of awk code: Simple explanation of awk program would be, using match function of awk to match regex to match version, once match is found print the matched value and exit from program.