Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash regex string variable match

Tags:

regex

bash

perl

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.

like image 736
The Georgia Avatar asked Jun 21 '16 04:06

The Georgia


People also ask

How do I check if a string matches in regex Bash?

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.

What is Bash_rematch?

$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.

What is =~?

The =~ operator is a regular expression match operator. This operator is inspired by Perl's use of the same operator for regular expression matching.


1 Answers

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

like image 144
xxfelixxx Avatar answered Sep 21 '22 03:09

xxfelixxx