Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting version number from a filename

Tags:

string

linux

bash

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

like image 240
Abeed Salam Avatar asked Oct 25 '12 22:10

Abeed Salam


3 Answers

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 ~]$ 
like image 118
ghoti Avatar answered Nov 06 '22 23:11

ghoti


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.

like image 36
Nikos C. Avatar answered Nov 06 '22 23:11

Nikos C.


Try:

current_ver=$(find /mnt/builds/current -name '*.run'|grep -Eo '[0-9]+\.[0-9]+')
like image 4
cEz Avatar answered Nov 06 '22 22:11

cEz