Extracting version number from a filename Extracting version number from a filename linux linux

Extracting version number from a filename


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 $versx86_64-XXX.XX-diagnostic.run[ghoti@pc ~]$ vers=${vers#*-}; echo $versXXX.XX-diagnostic.run[ghoti@pc ~]$ vers=${vers%-*}; echo $versXXX.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 $versinstaller-x86_64-XXX.XX[ghoti@pc ~]$ vers=${vers##*-}; echo $versXXX.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 $versXXX.XX[ghoti@pc ~]$ vers=$(sed -ne 's/-[^-]*$//;s/.*-//;p' <<<"$name")[ghoti@pc ~]$ echo $versXXX.XX[ghoti@pc ~]$ vers=$(cut -d- -f3 <<<"$name")[ghoti@pc ~]$ echo $versXXX.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]+')