Home > Net >  AWK command to fetch a value from the string s-pub-comtec-sap-product-app-1.0.0-mule-app.war
AWK command to fetch a value from the string s-pub-comtec-sap-product-app-1.0.0-mule-app.war

Time:10-31

I have a value s-pub-comtec-sap-product-app-1.0.0-mule-application.war I need to fetch the value 1.0.0 from the above string.

I have used

 echo "s-pub-comtec-sap-product-app-1.0.0-mule-application.war" | awk -F '-' '{ print $7 }'

and it worked.

But now the problem is sometimes the value will be s-pub-comtec-sap-app-1.0.0-mule-application.war, in this case my code will not fetch the 1.0.0 value.

Can you please suggest which command will achieve this scenario?

I have given below command which will not work in all the cases.

echo "s-pub-comtec-sap-product-app-1.0.0-mule-application.war" | awk -F '-' '{ print $7 }'

CodePudding user response:

If the substring you want to extract consists of digits and dots only, preceded by a - character, I would suggest a sed solution:

s='s-pub-comtec-sap-app-1.0.0-mule-application.war'
echo "$s" | sed -E 's/.*-([0-9](\.[0-9] ) ).*/\1/'

By the same token, an awk solution might be:

echo "$s" |
awk 'match($0,/-[0-9](\.[0-9] ) /) { print substr($0,RSTART 1,RLENGTH-1) }'
  • Related