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.
You can use the test construct, [[ ]] , along with the regular expression match operator, =~ , to check if a string matches a regex pattern (documentation). where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.
$BASH_REMATCH is an array and contains the matched text snippets. ${BASH_REMATCH[0]} contains the complete match. The remaining elements, e.g. ${BASH_REMATCH[1]} , contain the portion which were matched by () subexpressions.
The =~ operator is a regular expression match operator. This operator is inspired by Perl's use of the same operator for regular expression matching.
You can use regular expression in bash, just like in 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With