Rijin
Rijin

Reputation: 102

regex parsing a string to extract numbers in shell script

How can i parse the string below to extract version number and release number from the filename string below.

program-product_3.0.1009-5-XY1.0.456-1_i386.deb

Here I'm interested in getting

Version number : 3.0.1009
Release number : 5 

I tried grep, awk and sed and I`m not able to get it quite right.

The string follows the pattern,

Filename_Version-Release-OtherDependentPackageNameAndVersion-Release_Arch.deb. 

Please note that the naming convention is out of my control.

Upvotes: 2

Views: 1609

Answers (3)

Cole Tierney
Cole Tierney

Reputation: 10314

Here's an awk version:

awk -F'[_-]' '{print "Version number : "$3; print "Release number : "$4}'

Upvotes: 2

konsolebox
konsolebox

Reputation: 75488

With early bash version 2.05b or newer:

#!/bin/bash
F='program-product_3.0.1009-5-XY1.0.456-1_i386.deb'
IFS=- read V R __ <<< "${F#*_}"
printf 'Version number : %s\nRelease number : %s\n' "$V" "$R"

Run with:

bash script.sh

Output:

Version number : 3.0.1009
Release number : 5

Upvotes: 0

anubhava
anubhava

Reputation: 785146

Using pure BASH:

s='program-product_3.0.1009-5-XY1.0.456-1_i386.deb'
[[ "$s" =~ _([^-]+)-([^-]+) ]] && echo "${BASH_REMATCH[1]} : ${BASH_REMATCH[2]}"
3.0.1009 : 5

Upvotes: 3

Related Questions