Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strip version from package name using Bash

I'm trying to strip the version out of a package name using only Bash. I have one solution but I don't think that's the best one available, so I'd like to know if there's a better way to do it. by better I mean cleaner, easier to understand.

suppose I have the string "my-program-1.0" and I want only "my-program". my current solution is:

#!/bin/bash

PROGRAM_FULL="my-program-1.0"
INDEX_OF_LAST_CHARACTER=`awk '{print match($0, "[A-Za-z0-9]-[0-9]")} <<< $PROGRAM_FULL`
PROGRAM_NAME=`cut -c -$INDEX_OF_LAST_CHARACTER <<< $PROGRAM_FULL`

actually, the "package name" syntax is an RPM file name, if it matters.

thanks!

like image 981
cd1 Avatar asked May 24 '10 17:05

cd1


2 Answers

Pretty well-suited to sed:

# Using your matching criterion (first hyphen with a number after it
PROGRAM_NAME=$(echo "$PROGRAM_FULL" | sed 's/-[0-9].*//')

# Using a stronger match
PROGRAM_NAME=$(echo "$PROGRAM_FULL" | sed 's/-[0-9]\+\(\.[0-9]\+\)*$//')

The second match ensures that the version number is a sequence of numbers separated by dots (e.g. X, X.X, X.X.X, ...).

Edit: So there are comments all over based on the fact that the notion of version number isn't very well-defined. You'll have to write a regex for the input you expect. Hopefully you won't have anything as awful as "program-name-1.2.3-a". Absent any additional request from the OP though, I think all the answers here are good enough.

like image 112
Cascabel Avatar answered Nov 09 '22 12:11

Cascabel


Bash:

program_full="my-program-1.0"
program_name=${program_full%-*}    # remove the last hyphen and everything after

Produces "my-program"

Or

program_full="alsa-lib-1.0.17-1.el5.i386.rpm"
program_name=${program_full%%-[0-9]*}    # remove the first hyphen followed by a digit and everything after

Produces "alsa-lib"

like image 4
Dennis Williamson Avatar answered Nov 09 '22 12:11

Dennis Williamson