Search code examples
perlcisco

Joining multiple lines to one and hacking contents


This is the configuration I have, and I'm trying to consolidate this into a single route command that i could paste into a Cisco ASA.

set device "internal"
set dst 13.13.13.13 255.255.255.255
set gateway 172.16.1.1

set device "internal"
set dst 14.14.14.14 255.255.255.255
set gateway 172.16.1.1

set device "internal"
set dst 15.15.15.15 255.255.255.255
set gateway 172.16.1.1

Join it to a single device, then modify it accordingly to end up looking something like this

route internal 13.13.13.13 255.255.255.255 172.161.1.1

then the other 3 lines can go away.

I'd like to do this in Perl since i'm writing other scripts to do other portions of the source configuration


Solution

  • Assuming that your order is always device,dst,gateway then this works:

    use strict;
    use warnings;
    
    
    my @devices=(); #Array to store device strings
    my $current_device=""; #String to capture current device.
    
    while(<DATA>)
    {
        chomp;
        if(/^set (\w+) (.+)$/)
        {
            if($1 eq "device")
            {
                $current_device="route $2";
                $current_device=~s/"//g;
            }
            elsif($1 eq "dst")
            {
                $current_device.=" $2";
            }
            elsif($1 eq "gateway")
            {
                $current_device.=" $2";
                push @devices,$current_device;
            }
        }
    }
    
    print "$_\n" foreach(@devices);
    
    
    
    
    __DATA__
    set device "internal"
    set dst 13.13.13.13 255.255.255.255
    set gateway 172.16.1.1
    
    set device "internal"
    set dst 14.14.14.14 255.255.255.255
    set gateway 172.16.1.1
    
    set device "internal"
    set dst 15.15.15.15 255.255.255.255
    set gateway 172.16.1.1
    

    The output is:

    route internal 13.13.13.13 255.255.255.255 172.16.1.1
    route internal 14.14.14.14 255.255.255.255 172.16.1.1
    route internal 15.15.15.15 255.255.255.255 172.16.1.1