-   Programming (
-   -   [Perl] Reading multiple lines from a file (

Ziddy 10-29-2012 02:21 PM

[Perl] Reading multiple lines from a file
Hey there.
I'm not too sure how to phrase this, which seems to be why I'm having such a hard time finding an answer.
What I'm trying to do is...
Open a file and read the line. Say the line looks like this. "IP_Address username password". I want the IP in one variable, the UN in another and the PW in another. Then I do what I wish with them through other code, once finished, it moves on to the next line, formatted the same way. (IP UN PW).

Sorry that sounds so confusing. I know how read the entire line, then execute code and continue to the next, just not with arguments AFTER, on the same line.

Thanks for your time.

Habitual 10-29-2012 02:48 PM

Without knowing how much perl skill you have, here's a basic workup on opening a file and reading line-by-line while looking for text.

This code probably does NOT work OOTB. so some Perl kung-fu will be necessary.


my $dataFile = "/path/to/my/file";
open LOG, "<$dataFile";
while (<LOG>) {
$line = $_;
next if ($line=~ /^\s*#/); # ignore comment lines
 if($line =~ /(\d+\.\d+\.\d+\.\d+)(\w+)(\w+)/)
 print "$1 $2 $3\n";

I wrote a similar functioning script here... that probably can be modified to suit your purpose.
Without some sample data it would be a guessing game at best.

Ziddy 10-29-2012 03:11 PM

I evidently need to learn more about built in commands.
it spits out the ip for $1, but a number for $2/$3. Single digit.

Let's say in the file we have hello world world hello

$1 =
$2 = hello
$3 = world
is what I'm after. Then it executes code after assigning variables, moves on to the next line in the file, overwriting the variables, repeats until end of file. $1 becomes after it's done with the line. I know I'm making this more complicated than it has to be, as I usually do. Thanks fr your reply, I'm still messing with it.

Edit: I believe I'm on to something here. The only problem is not all lines have 3 arguments which seems to mess with it.

Edit2: Figured it out. Works quite well. Thanks for all the help. For those wondering:

open(INPUT_FILE, "check.txt") or die "check.txt NOT FOUND!\n";
my @list = <INPUT_FILE>;
for my $line (@list) {
if($line =~ /(\d+\.\d+\.\d+\.\d+) (\w+) (\w+)/) {
print "Checking $1 - $2 - $3:\t ";
etc etc.

Habitual 10-30-2012 08:27 AM

Your Perl.fu is better than mine. :hattip:

All times are GMT -5. The time now is 10:03 AM.