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
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
You may use:
awk 'match($0, /[0-9]+(\.[0-9]+)+/) {
print $0, substr($2, RSTART, RLENGTH)}' file
1) 2.343
2) 2.343.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With