LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   replacing awk with perl (https://www.linuxquestions.org/questions/linux-newbie-8/replacing-awk-with-perl-820161/)

casperdaghost 07-16-2010 06:19 AM

replacing awk with perl
 
I want the output of this file to be in a column, not next to each ohter. I tired putting a a newline escape character in a few places, but it breaks the script. It is easy in awk, just ls -ltr | awk '{print $8 }'

casper@casper-laptop:~$ pwd
/home/casper
casper@casper-laptop:~$ ls -ltr > /tmp/outfile
casper@casper-laptop:~$ cat -n /tmp/moreawkreplace
1 #!/usr/bin/perl
2 @eighth_column;
3 while ($line =<>) {
4 push (@eighth_column, (split(/\s+/, $line))[7]);
5 }
6 print join(' ', @eighth_column);
casper@casper-laptop:~$ /tmp/moreawkreplace /tmp/outfile
this is the output:::

colemak.typ colemak-1.0 colemak-1.0.tar.gz colemak-1.0.tar Examples Templates Public Music bang.sh

MTK358 07-16-2010 06:56 AM

Code:

#!/usr/bin/env perl

open my $file, "ls -ltr |" or die "Could not run ls";
while (<$file>) {
    my $col = split;
    $col = $col[7];
    print "$col\n";
}
close $file;

But for this application, I think awk is better. Or even the simple cut command.


All times are GMT -5. The time now is 10:40 PM.