使用 Bash 从包名中剥离版本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2899002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:07:41  来源:igfitidea点击:

strip version from package name using Bash

bashshellstring-parsing

提问by cd1

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.

我正在尝试仅使用 Bash 从包名称中删除版本。我有一个解决方案,但我认为这不是最好的解决方案,所以我想知道是否有更好的方法来做到这一点。更好我的意思是更清晰,更容易理解。

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

假设我有字符串“my-program-1.0”,而我只想要“my-program”。我目前的解决方案是:

#!/bin/bash

PROGRAM_FULL="my-program-1.0"
INDEX_OF_LAST_CHARACTER=`awk '{print match(
# 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]\+\)*$//')
, "[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.

实际上,“包名”语法是一个 RPM 文件名,如果重要的话。

thanks!

谢谢!

采纳答案by Cascabel

Pretty well-suited to sed:

非常适合 sed:

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

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

第二个匹配确保版本号是由点分隔的数字序列(例如 X, XX, XXX, ...)。

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.

编辑:因此,基于版本号的概念不是很明确这一事实,到处都有评论。您必须为您期望的输入编写一个正则表达式。希望你不会有像“program-name-1.2.3-a”那样糟糕的东西。虽然没有来自 OP 的任何额外要求,但我认为这里的所有答案都足够好。

回答by Paused until further notice.

Bash:

重击:

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 "my-program"

制作“我的程序”

Or

或者

$ echo my-program-1.0 | perl -pne 's/-[0-9]+(\.[0-9]+)+$//'
my-program

Produces "alsa-lib"

产生“alsa-lib”

回答by Jon Ericson

How about:

怎么样:

##代码##