[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1662
  • Last Modified:

awk in perl

system("awk '{print $1 $2 $3}' temp.txt");

I expect only the first 3 columns of the file to get printed. But it prints out all the columns, Why is that?
Thanks
Thomas
0
gr8thomas
Asked:
gr8thomas
  • 2
  • 2
1 Solution
 
ozoCommented:
system(q"awk '{print $1 $2 $3}' temp.txt");
0
 
TintinCommented:
Why would you even consider forking a process to call awk from Perl, when Perl is a superset of awk?

You can use a2p to convert an awk script to Perl (although the results can be  a little ugly), but for something as basic as what you have, just use:

#!/usr/bin/perl
while (<>) {
   chomp;
   @field = split;
   print "$field[0] $field[1] $field[2]\n";
}
0
 
ozoCommented:
perl -ane 'print"@F[0..2]\n"'
0
 
EarleAkeCommented:
My guess is by the time is reaching the shell, you do not have anything defined for $1, $2 or $3.  When it hits awk, the command has then become:

system("awk '{print }' temp.txt");

which would print out all the columns of the file.

How about this instead of the system call:

open(FILE, "<temp.txt");
while($line=<FILE>) {
  (@F) = split(" ", $line);
  printf ("%s\n", join(" ", @F[0..2]));
}
close(FILE);
0
 
TintinCommented:
If you are forking out to do awk in Perl, you're completely missing the point of using Perl.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now