Link to home
Start Free TrialLog in
Avatar of dev8
dev8

asked on

Quick Perl script to grep keywords

Hello,

Can someone show me a quick and dirty perl script that can take a file with a range of IPs and grep out IPs that are specified in another file?  For instance, I have 192.168.0.0-192.168.255.255 and I want to filter out about 100 IPs from that range and make a new file with those IPs still remaining.  Thanks for any help!

//j
Avatar of ZiaTioN
ZiaTioN

I think I understand what you want. If you are going to be dealing with more than just the last octet of the IP addresses then more code would be required.

#!/usr/bin/perl -w

die "Required user input missing!\n" if ($#ARGV < 0);
my $start = $ARGV[0];
my $end   = $ARGV[1];

open(FILE, "<", "ip.txt") || die "Can't open file: $!\n";
open(OUT, ">>", "out.txt") || die "Can't open out.txt: $!\n";
while (<FILE>) {
   my $i = $1 if (/\d+\.\d+\.\d+\.(\d+)/);
   print OUT if (($i <= $end) && ($i >= $start));
}
close(OUT);
close(FILE);
print "Done!\n";


Hope this helps ya!
Oh I forgot to mention that I assumed the source IP address list would be delimited by newlines (\n) in the file, meaning one IP address on each line. If this is not the case this code will need to be altered.
Avatar of dev8

ASKER

ZiaTioN,

With the above script, I specified with input already in it like so:

ip.pl ip.txt

The resulting file was an out.txt that returned the same information that was in the ip.txt file.  I ran it again and it just appended the same info in ip.txt to the existing out.txt. I was hoping that it would work like the following:

ip.pl ip.txt remove.txt

ip.pl is the script
ip.txt is where a list of IPs exist
remove.txt contains the list of IPs to remove from the ip.txt
a resulting file by the name of "out.txt" would be created and show the remaining IPs after specified IPs (in the remove.txt) were removed.  

Thanks for any more help!

ASKER CERTIFIED SOLUTION
Avatar of ZiaTioN
ZiaTioN

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dev8

ASKER

Thanks Zia, that worked for me!
Avatar of ozo
  my $i = $1 if (/\d+\.\d+\.\d+\.(\d+)/);
careful, if the regex does not match, $i will retain it's previous value
Actually it will not. With the "my" inside the loop each iteration re-initializes the variable (to null). All that will happen if the pattern does not find a match is that $i will remain undefined and the script will generate en error message complaining about an undefined variable in comparison (lt, gt, etc).