Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to extract version number

Tags:

regex

sed

I want to extract the version number from the ld -v command and I have written the following sed expression:

ld -v | sed -r 's/.+([0-9|\.]+)/\1/'

However this outputs 1, which is the last digit of the version number. The result I expect is 2.35.1

Where did I go wrong with my regular expression? How I understand it the .+ part matches all characters and whitespace and ([0-9|\.]+) matches a digit or a dot and then captures this. \1 then references the captured bit.

like image 958
TPens Avatar asked Jan 25 '23 13:01

TPens


2 Answers

Use GNU grep like so:

ld -v | grep -Po '[\d.]+' | head -n1

Output:

2.25.1

Here, grep uses the following options:
-P : Use Perl regexes.
-o : Print the matches only (1 match per line), not the entire lines.

[\d.]+ : Any digit or a literal dot, repeated 1 or more times.

SEE ALSO:
grep manual
perlre - Perl regular expressions

like image 184
Timur Shtatland Avatar answered Jan 29 '23 16:01

Timur Shtatland


With awk could you please try following, written and tested in GNU awk.

ld -v | 
awk 'match($0,/([0-9]+\.){1,}[0-9]+$/){print substr($0,RSTART,RLENGTH)}'

Explanation: Adding detailed explanation for above.

ld -v |                                ##Running ld -v command and sending output to awk program from here.
awk '                                  ##Starting awk program from here.
match($0,/([0-9]+\.){1,}[0-9]+$/){     ##using match function to match digits followed by dot with 1 ore more occurrences and then digits till last of line.
  print substr($0,RSTART,RLENGTH)      ##Printing sub string of matched regex which prints from RSTART to till RLENGTH values.
}'
like image 21
RavinderSingh13 Avatar answered Jan 29 '23 14:01

RavinderSingh13