I'm trying to strip the version out of a package name using only Bash. I have one solution but I don't thi开发者_Go百科nk 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!
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.
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"
How about:
$ echo my-program-1.0 | perl -pne 's/-[0-9]+(\.[0-9]+)+$//'
my-program
精彩评论