Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Regular expression query

by Anonymous Monk
on Nov 12, 2017 at 17:20 UTC ( [id://1203224]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to do the following grep for my output

A> show chassis power | match "PEM|Online" PEM 0: PEM 1: PEM 2: State: Online PEM 3: State: Online

In the above output am trying to find which PEM is online. For this , i thought i split using /n and find the state Online and go back to previous matching and check which PEM is online . I did not complete the code as am stuck how to go back

$rh->cmd('show chassis power | match "PEM|Online"'); my $output = $rh->get_response; my @outputlist = split /\n+/, $output; foreach (0..$#outputlist) { if ($outputlist[$_] =~/ State:\s\w{4}Online/) { if($outputlist[$_ _1] =~ /PEM 1/ } }

Replies are listed 'Best First'.
Re: Regular expression query
by hippo (Bishop) on Nov 12, 2017 at 18:11 UTC

    If you split on the blank lines instead of on newlines then you don't have to go back:

    #!/usr/bin/env perl use strict; use warnings; my $input = qq# PEM 0: PEM 1: PEM 2: State: Online PEM 3: State: Online #; for my $rec (split /\n\n/, $input) { next unless $rec =~ /State:\s+Online/; $rec =~ /(PEM \d+)/ or die "Bad input: no PEM in '$rec'!"; print "$1 is online\n"; }
Re: Regular expression query
by BillKSmith (Monsignor) on Nov 12, 2017 at 22:35 UTC
    With the /m flag, a regex can match over more than one line.
    C:\Users\Bill\forums\monks>type 1203224.pl use strict; use warnings; my $output = <<'END_OUT'; PEM 0: PEM 1: PEM 2: State: Online PEM 3: State: Online END_OUT while ($output =~ m/^(PEM\s\d) \: $ \n ^ \s\sState: [ ]+ (Online)$/xmg +) { print "$1 $2\n"; } C:\Users\Bill\forums\monks>perl 1203224.pl PEM 2 Online PEM 3 Online
    Bill
Re: Regular expression query
by KurtZ (Friar) on Nov 12, 2017 at 17:57 UTC
    The simplest solution is to always parse the PEM and store it in a variable. Like this you only need to print that variable out if you have a match.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1203224]
Approved by davies
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-04-19 19:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found