简体   繁体   English

Bash 正则表达式字符串变量匹配

[英]Bash regex string variable match

I have the following script i wrote in perl that works just fine.我有以下用 perl 编写的脚本,效果很好。 But i am trying to achieve the same thing using bash.但我正在尝试使用 bash 来实现同样的目的。

#!/usr/bin/perl

use 5.010;
use strict;

INIT {
    my $string = 'Seconds_Behind_Master: 1';
    my ($s) = ($string =~ /Seconds_Behind_Master: ([\d]+)/);
    if ($s > 10) {
        print "Too long... ${s}";
    } else {
        print "It's ok";
    }
}

__END__

How can i achieve this using a bash script?我如何使用 bash 脚本实现这一目标? Basically, i want to be able to read and match the value at the end of the string "Seconds_Behind_Master: N" where N can be any value.基本上,我希望能够读取和匹配字符串“Seconds_Behind_Master: N”末尾的值,其中 N 可以是任何值。

You can use regular expression in bash, just like in perl.您可以在 bash 中使用正则表达式,就像在 perl 中一样。

#!/bin/bash

STRING="Seconds_Behind_Master: "

REGEX="Seconds_Behind_Master: ([0-9]+)"

RANGE=$( seq 8 12 )

for i in $RANGE; do
    NEW_STRING="${STRING}${i}"
    echo $NEW_STRING;

    [[ $NEW_STRING =~ $REGEX ]]
    SECONDS="${BASH_REMATCH[1]}"
    if [ -n "$SECONDS" ]; then
        if [[ "$SECONDS" -gt 10 ]]; then
            echo "Too Long...$SECONDS"
        else
            echo "OK"
        fi
    else
        echo "ERROR: Failed to match '$NEW_STRING' with REGEX '$REGEX'"
    fi
done

Output输出

Seconds_Behind_Master: 8
OK
Seconds_Behind_Master: 9
OK
Seconds_Behind_Master: 10
OK
Seconds_Behind_Master: 11
Too Long...11
Seconds_Behind_Master: 12
Too Long...12

man bash #BASH_REMATCH 男人 bash #BASH_REMATCH

You can use a tool for it eg sed if you want to stay with regexps:如果你想继续使用正则表达式,你可以使用一个工具,例如sed

#!/bin/sh
string="Seconds_Behind_Master: 1"
s=`echo $string | sed -r 's/Seconds_Behind_Master: ([0-9]+)/\1/g'`
if [ $s -gt 10 ]
then
    echo "Too long... $s"
else
    echo "It's OK"
fi

The specific case of "more than a single digit" is particularly easy with just a pattern match: “多于一位数”的特定情况仅通过模式匹配就特别容易:

case $string in
   *Seconds_Behind_Master: [1-9][0-9]*) echo Too long;;
   *) echo OK;;
esac

To emulate what your Perl code is doing more closely, you can extract the number with simple string substitutions.要更接近地模拟 Perl 代码正在执行的操作,您可以使用简单的字符串替换来提取数字。

s=${string##*Seconds_Behind_Master: }
s=${s%%[!0-9]*}
[ $s -gt 10 ] && echo "Too long: $s" || echo OK.

These are glob patterns, not regular expressions;这些是 glob 模式,而不是正则表达式; * matches any string, [!0-9] matches a single character which is not a digit. *匹配任何字符串, [!0-9]匹配单个非数字字符。 All of this is Bourne-compatible, ie not strictly Bash only (you can use /bin/sh instead of /bin/bash ).所有这些都是与 Bourne 兼容的,即不只是严格意义上的 Bash(您可以使用/bin/sh而不是/bin/bash )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM