Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match and extract two version number patterns

Tags:

regex

awk

I am trying to write a regular expression that will match the version number from a configuration file. I am trying to match and extract the version number from the two following numbering patterns

1) <version>2.343</version>
2) <version>2.343.2</version>

Such that a result is returned of either

1) 2.343
2) 2.343.2

My current solution- looks like either one of these two awk commands with the regex pattern to match both cases individually. But there must be a solution that covers both cases?

awk 'match($0, /[0-9][.][0-9][0-9][0-9]/) {print substr($0, RSTART, RLENGTH) }' config.xml
awk 'match($0, /[0-9][.][0-9][0-9][0-9].[0-9]/) {print substr($0, RSTART, RLENGTH) }' config.xml
like image 907
Bert Avatar asked Jul 10 '26 17:07

Bert


2 Answers

1st solution: With your shown samples please try following. Using match function of awk here, should work in any POSIX awk version. Using regex >[0-9]+(\.[0-9]+)*< to match values from > followed by version followed by > and if regex match is found then printing sub string of matched values.

awk 'match($0,/>[0-9]+(\.[0-9]+)*</){print substr($0,RSTART+1,RLENGTH-2)}' Input_file

OR In case you want to exactly looking for version tag then try following:

awk 'match($0,/<version>[0-9]+(\.[0-9]+)*<\/version>/){print substr($0,RSTART+9,RLENGTH-19)}'  Input_file


2nd solution: With your shown samples. Using GNU awk's RS variable with same concept of using regex in it and getting values.

awk -v RS='<version>[0-9]+(\\.[0-9]+)*<\\/version>' 'RT{split(RT,arr,"[><]");print arr[3]}' Input_file
like image 142
RavinderSingh13 Avatar answered Jul 14 '26 14:07

RavinderSingh13


You may use:

awk 'match($0, /[0-9]+(\.[0-9]+)+/) {
   print $0, substr($2, RSTART, RLENGTH)}' file

1) 2.343
2) 2.343.2
like image 28
anubhava Avatar answered Jul 14 '26 14:07

anubhava