来自命令输出的字符串比较

时间:2019-10-08 08:47:29

标签: bash

我有一个包含以下文本的文件。

{
    "Version": "2012-10-17",
    "Id": "Policy1563368389080",
    "Statement": [
        {
            "Sid": "Stmt1563368385984",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": [
                "arn:aws:s3:::mybucketname/*",
                "arn:aws:s3:::mybucketname"
            ]
        }
    ]
}

我正在尝试对最后一次出现状态之后的文本进行字符串比较:

            channel: stable
  installed-version: 6.45.6
             status: finding out latest version...

            channel: stable
  installed-version: 6.45.6
     latest-version: 6.45.6
             status: System is already up to date

我的脚本如下:

System is already up to date

我注意到分配给$ GOOD的字符串的长度为29个字符,而$ STATUS为30个字符,因此根据建议,我将它们都通过管道传递给XXD。

注意到$ STATUS有0d(回车符),并使用GOOD="status: System is already up to date" STATUS=$(cat file.txt | grep status | tail -1 | tr -d '\r' ) if [ "$STATUS" != "$GOOD" ] then echo "There is a new version available" else echo "You are up to date" 将其删除。

现在两个字符串都在十六进制中匹配,但是比较仍然失败。

tr -d '\r'

2 个答案:

答案 0 :(得分:0)

状态前您有空格。使用xargs代替tr -d'\ r'。

GOOD="status: System is already up to date"

STATUS=$(grep status file.txt | tail -1 | xargs)

if [ "$STATUS" != "$GOOD" ]
then
    echo "There is a new version available"
else
    echo "You are up to date"
fi

答案 1 :(得分:0)

如何将pattern matching[[ .. ]]命令一起使用,而不是 [test命令。 这是用法的一个小例子:

target="aaa"
string="   aaa___"

if [[ $string == *$target* ]]; then
    echo "match"
fi

您不必担心开头/结尾的多余字符 模式匹配。
然后您可以说:

good="status: System is already up to date"
status=$(grep "status" "file.txt" | tail -1)

if [[ $status == *$good* ]]; then
     echo "You are up to date"
else
     echo "There is a new version available"
fi

请注意,您不必在[[和]]中将变量加双引号。
希望这会有所帮助。