gr8thomas
asked on
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
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
perl -ane 'print"@F[0..2]\n"'
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);
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);
If you are forking out to do awk in Perl, you're completely missing the point of using Perl.
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";
}