Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

1st time perl user requires help 1

Status
Not open for further replies.

paulonline

Technical User
Apr 23, 2009
2
FR
Hi all,

I have a question regarding perl that I hope you can help with.

I am trying to create an array from a hosts file, while at the same time removing unwanted lines, also i want to store only 2 of the colums from the file into the array.

--- hosts file example ---
#start of hosts file
10.0.2.10 machine1 mdlocal service1 service2
10.0.2.11 machine2 mdlocal service1 service2
#middle of hosts file

10.0.2.12 machine3 mdlocal service1
10.0.2.13 machine4

#end of hosts file

If I use the following code (with awk script I get the following output)

@get_host_list = `/usr/bin/grep mdlocal hosts | grep -v \"#\" | /usr/bin/awk \'\{print \$2,\$1\}\' | /usr/bin/sort -u` ;

print @get_host_list ;

output :-
machine1 10.0.2.10
machine2 10.0.2.11
machine3 10.0.2.12

So using perl only how would I extract column 1 & 2 and put only those values into the array.

Cheers
Paul
 
Hi

Like this ?
Code:
#!/usr/bin/perl

while (<DATA>) {
  chomp;
  $temp{join ' ',(split /\s+/)[1,0]}=1 if m/^[^#].*mdlocal/
}

@get_host_list=sort keys %temp;

print "$_\n" foreach (@get_host_list);

__DATA__
#start of hosts file
10.0.2.10 machine1 mdlocal service1 service2
10.0.2.11 machine2 mdlocal service1 service2
#middle of hosts file

10.0.2.12 machine3 mdlocal service1
10.0.2.13 machine4

#end of hosts file
Please use meaningful subjects in the future.

Feherke.
 
This only offers an additional exercise with alternative pattern (hopefully tightening up to filter some undesired output, amid perhaps more exotic) and settings.
[tt]
#your givens here
[green]my $hostfile="c:\xyz\hosts";
my $outfile="c:\xyz\out.txt";[/green]

open(SRC,"<",$hostfile) or die "can't open $hostfile: $!";
open(TGT,">",$outfile) or die "can't open $outfile: $!";

while (<SRC>) {
if (/^\s*([^#\s]*?)\s+([^#\s]+?)\s+mdlocal.*$/) {
print TGT "$2 $1\n";
}
}

close TGT;
close SRC;[/tt]
 
amendment
I've intended to forward slash the paths.
[tt]
#your givens here
[green]my $hostfile="c:[red]/[/red]xyz[red]/[/red]hosts";
my $outfile="c:[red]/[/red]xyz[red]/[/red]out.txt";[/green]
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top