How do I extract the version number portion from the version string?
How do I extract the version number from string=customer-asset-tag-1.0.2.9
?
Desired result:
Component= customer-asset-tag
version number=1.0.2.9
There are many ways of doing this, for example:
-
bash and similar shells (see here for more info)
$ string=customer-asset-tag-1.0.2.9 $ echo -e "Component: ${string:0:18}\nVersion: ${string:19}" Component: customer-asset-tag Version: 1.0.2.9
-
awk
$ echo $string | awk -F- -v OFS=- '{print "Component: "$1,$2,$3; print "Version: "$4}' Component: customer-asset-tag Version: 1.0.2.9
Here, we are setting
awk
's field delimiter to-
(this is used to define fields, the 1st field is$1
, the 2nd$2
etc). We are also setting the output field separator to-
so it will print correctly. -
perl
$ echo $string | perl -ne '/(.*)-([^-]+)/; print "Component: $1\nVersion: $2"' Component: customer-asset-tag Version: 1.0.2.9
This is the most robust and general of the three approaches since it simply looks for the longest string of non
-
characters and saves that as the version and everything before the version until the last-
and saves that as a component.
To extract version number
echo "customer-asset-tag-1.0.2.9" | sed 's/[a-z-]//g'
Perl way of doing it
echo "customer-asset-tag-1.0.2.9" | perl -ne '/([a-z-]*)-([\d+.+]*)/; print "Component= $1\nVersion= $2\n"'
Use the following in terminal,
$ string=customer-asset-tag-1.0.2.9
$ ver=$(echo $string | awk -F- '{print $NF}')
$ Component=${string/-$ver/}
$ echo "version number=$ver"
version number=1.0.2.9
$ echo "Component=$Component"
Component=customer-asset-tag
or inside a shell script,
#!/bin/bash
string=customer-asset-tag-1.0.2.9
ver=$(echo $string | awk -F- '{print $NF}')
Component=${string/-$ver/}
echo "version number=$ver"
echo "Component=$Component"
Another awk
command,
$ string=customer-asset-tag-1.0.2.9
$ echo "Component= "$(echo $string | awk '{print substr($1,1,18)}') && echo "Version number="$(echo $string | awk '{print substr($1,20)}')
Component= customer-asset-tag
Version number=1.0.2.9
Description:
echo $string
- displays the value assigned to variable string.-
echo $string | awk '{print substr($1,1,18)}'
| - standard output was fed as input to the following command.
substr($1,1,18)
- From the input take the first column and display only the characters starting from the position 1 to 18 to the standard output.
-
echo $string | awk '{print substr($1,20)}'
- Display the characters starting from the 20th position in the first column from the standard input.
awk '{print substr($x,y,z)}'
x - column number
y - starting position
z - Ending position