bash 从文件名中提取版本号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13078490/
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-18 03:38:21  来源:igfitidea点击:

Extracting version number from a filename

linuxstringbash

提问by Abeed Salam

I have a file in a folder like this:

我在这样的文件夹中有一个文件:

installer-x86_64-XXX.XX-diagnostic.run

安装程序-x86_64-XXX.XX-diagnostic.run

where XXX.XX is a version number and I need the version number only. How to do it in linux?

其中 XXX.XX 是版本号,我只需要版本号。在 linux 中如何实现?

I have this code:

我有这个代码:

#!/bin/bash
current_ver=$(find /mnt/builds/current -name '*.run'|awk -F/ '{print $NF}')

So this gives me just the name of the file correctly (minus the location, which I don't want).

所以这给了我正确的文件名(减去我不想要的位置)。

But how do I only get the XXX.XX version number into a variable such as $version

但是我如何只将 XXX.XX 版本号放入一个变量中,例如 $version

采纳答案by Nikos C.

You want:

你要:

awk -F"-" '{ print  }'

With -Fyou specify the delimiter. In this case, -. The version number is the third field, so that's why you need $3.

-F您指定分隔符。在这种情况下,-。版本号是第三个字段,所以这就是为什么你需要$3.

回答by ghoti

You actually don't need any external tools. You can do this entirely within bash, by chopping variables according to patterns..

您实际上不需要任何外部工具。您可以完全在 bash 中执行此操作,方法是根据模式切割变量。

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

回答by Cez

Try:

尝试:

current_ver=$(find /mnt/builds/current -name '*.run'|grep -Eo '[0-9]+\.[0-9]+')

回答by Alexander

People forget there is a simpler one, cut.

人们忘记了还有一个更简单的,cut.

$ echo "installer-x86_64-XXX.XX-diagnostic.run" | cut -d - -f 3
XXX.XX