I have a file in a folder like this:
installer-x86_64-XXX.XX-diagnostic.run
where XXX.XX is a version number and I need the version number only. How to do it in linux?
I have this code:
#!/bin/bash
current_ver=$(find /mnt/builds/current -name '*.run'|awk -F/ '{print $NF}')
So this gives me just the name of the file correctly (minus the location, which I don't want).
But how do I only get the XXX.XX version number into a variable such as $version
You actually don't need any external tools. You can do this entirely within bash, by chopping variables according to patterns..
[ghoti@pc ~]$ name="installer-x86_64-XXX.XX-diagnostic.run"
[ghoti@pc ~]$ vers=${name#*-}; echo $vers
x86_64-XXX.XX-diagnostic.run
[ghoti@pc ~]$ vers=${vers#*-}; echo $vers
XXX.XX-diagnostic.run
[ghoti@pc ~]$ vers=${vers%-*}; echo $vers
XXX.XX
[ghoti@pc ~]$
Or if you prefer, you can chop off pieces right-hand-side first:
[ghoti@pc ~]$ name="installer-x86_64-XXX.XX-diagnostic.run"
[ghoti@pc ~]$ vers=${name%-*}; echo $vers
installer-x86_64-XXX.XX
[ghoti@pc ~]$ vers=${vers##*-}; echo $vers
XXX.XX
[ghoti@pc ~]$
Of course, if you want to use external tools, that's fine too.
[ghoti@pc ~]$ name="installer-x86_64-XXX.XX-diagnostic.run"
[ghoti@pc ~]$ vers=$(awk -F- '{print $3}' <<<"$name")
[ghoti@pc ~]$ echo $vers
XXX.XX
[ghoti@pc ~]$ vers=$(sed -ne 's/-[^-]*$//;s/.*-//;p' <<<"$name")
[ghoti@pc ~]$ echo $vers
XXX.XX
[ghoti@pc ~]$ vers=$(cut -d- -f3 <<<"$name")
[ghoti@pc ~]$ echo $vers
XXX.XX
[ghoti@pc ~]$
You want:
awk -F"-" '{ print $3 }'
With -F
you specify the delimiter. In this case, -
. The version number is the third field, so that's why you need $3
.
Try:
current_ver=$(find /mnt/builds/current -name '*.run'|grep -Eo '[0-9]+\.[0-9]+')
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