首页 > 解决方案 > 如何捕获存储在 shell 脚本变量中的版本号的一部分

问题描述

我正在尝试解析bash脚本中的一些数据并测试版本号的第二部分。这是一些示例文本,存储在名为 的变量中myinfo

Application 2021:

Version: 16.3.2.151
--
Application 2020:

Version: 15.1.3.302

我只需要捕获以(在这种情况下)2021开头的版本的第二部分并测试它是否为 3 或更大。163

我从网络上的各种答案中尝试了许多看似相关的东西,但没有成功。

例如,我得到的最接近的是使用正则表达式(?:\b16\.)(\d)在 regexr 上找到 16.3,但我还没有弄清楚如何只捕获 3(如果我更了解正则表达式,可能很容易)。

更新:

感谢 Paul Hodges 的简洁回答。背景是我需要找到用户在他们的系统上拥有的确切版本的 Adob​​e InDesign。16.3 及更高版本要求脚本的其余部分有不同的行为。这适用于您需要知道应用程序版本号的任何情况。这是使用我选择的解决方案的最终脚本:

#!/bin/bash

# Ask system_profiler for information about all the installed applications
#  then use fgrep to pull out the line, and the 2 lines after, that starts with Adobe InDesign 2021
v=$(system_profiler SPApplicationsDataType | fgrep -A 2 ' Adobe InDesign 2021')

echo ${v}
#    Adobe InDesign 2021:
#
#      Version: 16.3.2.151

# Strip everything up to the first .
v="${v#*.}"
# Strip everything after the first . of the remaining text
v="${v%%.*}"

echo "${v}"
# 3

# Test if it is greater or equal to 3
if [[ "${v}" -ge 3 ]]; then
    echo Its 3 or greater
else
    echo Less than 3
fi

标签: bashshellparsing

解决方案


参数解析可以在几个步骤中完成,而无需运行子进程。

假设

x="Application 2021:

Version: 16.3.2.151
--
Application 2020:

Version: 15.1.3.302"

然后

x="${x#*.}"

从前面到第一个点剥离所有内容,并且

x="${x%%.*}"

从(现在)第一个 dor 到结束的所有内容。

echo $x
3

x因此,如果您的数据位于

x="${x#*.}"; echo ${x%%.*}

将输出3.

如果您想要更精确的解析,请激活扩展通配符。

$: shopt -s extglob
$: y="${x//*Application+([[:space:]])2021:+([[:space:]])Version:+([[:space:]])+([0-9])./}"
$: echo "${y%%.*}"
3

请记住这是globbing,而不是真正的正则表达式解析。
为此,请使用sedor awk,尽管这可以很好地完成工作。

有关 globbing 的更多详细信息,请参阅https://mywiki.wooledge.org/glob
有关基本参数解析的更多信息,请参阅https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion .html


推荐阅读