Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: split file on blank lines and match blocks

by kcott (Canon)
on Sep 09, 2012 at 10:26 UTC ( #992573=note: print w/replies, xml ) Need Help??


in reply to split file on blank lines and match blocks

As the data within define host{ ... } are effectively key/value pairs, you can capture that into a Perl hash then directly access host_name, address, etc. as required.

#!/usr/bin/env perl use strict; use warnings; my $define_re = qr{ \A define \s+ host \{ \s+ ( .*? ) \s+ \} \s* \z }m +sx; my $crit_dmz_re = qr{ (?> CRIT | DMZ ) }x; my $out_format = qq{%s (%s) in groups: %s\n}; local $/ = ''; while (<DATA>) { /$define_re/; my %block = ( split /\s+/ => $1 ); if ($block{hostgroups} =~ /$crit_dmz_re/) { printf $out_format => @block{qw{host_name address hostgroups}} +; } } __DATA__ define host{ use HALF host_name denlas02 alias denlas02 address 146.xxx.xxx.xxx hostgroups LINUX,DEN,DMZ } define host{ use HALF host_name ppplas11 alias ppplas11 address 10.xxx.xxx.xxx hostgroups LINUX,PPO,ORAPRD } define host{ use ALIVE host_name ppplas12 alias ppplas12 address 10.50.33.26 hostgroups LINUX,GRID,RMAN,CRIT }

Output:

$ pm_hosts_parse.pl denlas02 (146.xxx.xxx.xxx) in groups: LINUX,DEN,DMZ ppplas12 (10.50.33.26) in groups: LINUX,GRID,RMAN,CRIT

-- Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://992573]
help
Chatterbox?
[Corion]: LanX: Ah, yeah - Frankfurt is in the quake region, but at the very border. I think I've never noticed a quake in Frankfurt myself
[marto]: good morning all
[Corion]: On another topic, in the process of Rubber Duck SoPWing, I wrote a post about the best API for generating HTTP requests (not sending them) and while writing it and fleshing out my sample implementation, I came up with some improvements to my ...
[Corion]: ... existing prototype. Cartesian Products will be proud of that module once it gets out ;)
[Corion]: Hi marto ;)

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (9)
As of 2017-01-18 10:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you watch meteor showers?




    Results (161 votes). Check out past polls.