有没有办法在bash上比较这样的字符串,例如:2.4.52.82.4.5.1

推荐答案

下面是一个纯Bash版本,不需要任何外部实用程序:

#!/bin/bash
vercomp () {
    if [[ $1 == $2 ]]
    then
        return 0
    fi
    local IFS=.
    local i ver1=($1) ver2=($2)
    # fill empty fields in ver1 with zeros
    for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
    do
        ver1[i]=0
    done
    for ((i=0; i<${#ver1[@]}; i++))
    do
        if [[ -z ${ver2[i]} ]]
        then
            # fill empty fields in ver2 with zeros
            ver2[i]=0
        fi
        if ((10#${ver1[i]} > 10#${ver2[i]}))
        then
            return 1
        fi
        if ((10#${ver1[i]} < 10#${ver2[i]}))
        then
            return 2
        fi
    done
    return 0
}

testvercomp () {
    vercomp $1 $2
    case $? in
        0) op='=';;
        1) op='>';;
        2) op='<';;
    esac
    if [[ $op != $3 ]]
    then
        echo "FAIL: Expected '$3', Actual '$op', Arg1 '$1', Arg2 '$2'"
    else
        echo "Pass: '$1 $op $2'"
    fi
}

# Run tests
# argument table format:
# testarg1   testarg2     expected_relationship
echo "The following tests should pass"
while read -r test
do
    testvercomp $test
done << EOF
1            1            =
2.1          2.2          <
3.0.4.10     3.0.4.2      >
4.08         4.08.01      <
3.2.1.9.8144 3.2          >
3.2          3.2.1.9.8144 <
1.2          2.1          <
2.1          1.2          >
5.6.7        5.6.7        =
1.01.1       1.1.1        =
1.1.1        1.01.1       =
1            1.0          =
1.0          1            =
1.0.2.0      1.0.2        =
1..0         1.0          =
1.0          1..0         =
EOF

echo "The following test should fail (test the tester)"
testvercomp 1 1 '>'

运行测试:

$ . ./vercomp
The following tests should pass
Pass: '1 = 1'
Pass: '2.1 < 2.2'
Pass: '3.0.4.10 > 3.0.4.2'
Pass: '4.08 < 4.08.01'
Pass: '3.2.1.9.8144 > 3.2'
Pass: '3.2 < 3.2.1.9.8144'
Pass: '1.2 < 2.1'
Pass: '2.1 > 1.2'
Pass: '5.6.7 = 5.6.7'
Pass: '1.01.1 = 1.1.1'
Pass: '1.1.1 = 1.01.1'
Pass: '1 = 1.0'
Pass: '1.0 = 1'
Pass: '1.0.2.0 = 1.0.2'
Pass: '1..0 = 1.0'
Pass: '1.0 = 1..0'
The following test should fail (test the tester)
FAIL: Expected '>', Actual '=', Arg1 '1', Arg2 '1'

Linux相关问答推荐

抛出主,即未捕获到SIGSEGV中的异常结果

通过添加1位数字替换最后4位数字(不包括0x)

X86_64程序集中的分段故障:系统调用问题

Flutter 构建错误:';DART:JS_interop';在此平台上不可用

UTF-8输入和使用XGetICValues

在 Linux 中屏蔽文件中的位 - 按位运算

如何使用 gdb 调试堆栈分段错误?

bind(): "无法分配请求的地址"

Linux合并文件

如何将通配符参数传递给 bash 文件

在没有root访问权限的情况下安装zsh?

查看 linux 上的多核或多 CPU 利用率

适用于 Linux 和 Mac 的 HTTP 调试代理

如何在 linux ElementaryOS 中修复 Genymotion,但未找到错误CXXABI_1.3.8

如何以另一个用户的身份使用 sudo 在 bash 子shell 中执行一系列命令?

如何从 Linux 中的用户空间访问物理地址?

从文本文件中删除奇数行或偶数行

在没有 python 命令的情况下在终端中运行 python 脚本

使用 Bash 查找和复制文件

`cd //` 中的双斜杠 // 在 Linux 中是什么意思?