The Georgia The Georgia - 5 months ago 30
Perl Question

Bash regex string variable match

I have the following script i wrote in perl that works just fine. But i am trying to achieve the same thing using 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? 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.

Answer

You can use a tool for it e.g. sed if you want to stay with regexps:

#!/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