http://www.perlmonks.org?node_id=971746

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

Hi Chaps

Need some help with this, I’m attempting to try and read in the below which is system output for one of the NIC on my server.

2: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000 link/ether 00:0c:29:4e:97:a1 brd ff:ff:ff:ff:ff:ff

I want to be able to strip away all characters before eth1 including all white space and eveything after eth1: so I’m just left with eth1.

I have tried various regular expression but can’t seem to trap : unless you can think of a better way to do it.

Then print out back to the file handle just the NIC adapter name

This is what I have so far, not much to go on but should give oyu an idea of what im trying to do

#!/usr/bin/perl -w my $nicount = `ip link >/tmp/nic.txt`; open(NICFH, "/tmp/nic.txt") || die "can't open file: $!"; my @NIC = <NICFH>; foreach my $file (@NIC) { $file =~ s/\d\:\s//; print $file; }

Replies are listed 'Best First'.
Re: Remove text after and before
by johngg (Canon) on May 22, 2012 at 10:13 UTC

    Perhaps like this?

    knoppix@Microknoppix:~$ perl -E ' > $input = <<EOI; > 2: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast + state UP qlen 1000 link/ether 00:0c:29:4e:97:a1 brd ff:ff:ff:ff:ff:f +f > EOI > > $eth = ( split m{\s*:\s*}, $input )[ 1 ]; > say qq{->$eth<-};' ->eth1<- knoppix@Microknoppix:~$

    Cheers,

    JohnGG

      Thanks Guys

      You have been a great help looks like I have it sorted now

      Thanks again
Re: Remove text after and before
by Neighbour (Friar) on May 22, 2012 at 09:47 UTC
    You could replace your source data with this:
    my @NIC = split("\n", `ip link | sed -n 1~2p | cut -d':' -f2 | tr -d ' '`);
    and go from there, though that's not really the Perl way :P

    A more perlish way would be like this:
    my @raw_data = `ip link`; my @NIC = grep { /^\d+:\ /; } @raw_data; for (@NIC) { chomp; s/^[0-9]+:\ ([a-z]+[0-9]*):\ .*$/$1/; } Data::Dump::dd(@NIC);
    (For some reason map { s/^[0-9]+:\ ([a-z]+[0-9]*):\ .*$/$1/; } grep ... doesn't seem to work).
      (For some reason map { s/^[0-9]+:\ ([a-z]+[0-9]*):\ .*$/$1/; } grep ... doesn't seem to work).

      That's because s/// returns the number of substitutions, not the substituted string, and map picks up the return value of the block. So adding a $_; to the end of the block might help, then the block returns the substituted text.