How can I sort the output from an awk script?

时间:2015-08-06 13:54:10

标签: bash sorting unix awk

When I run check script, I get the o/p as below,

-rw-rw-r-- 1 noper sbcprd 9175 Aug 6 03:36 opLogDir    
-rw-rw-r-- 1 soper sbcprd 9104 Aug 6 03:04 opLogDir    
-rw-rw-r-- 1 moper sbcprd 9561 Aug 6 02:18 opLogDir    
-rw-rw-r-- 1 woper sbcprd 9561 Aug 6 05:06 opLogDir    
-rw-rw-r-- 1 boper sbcprd 9834 Aug 6 03:34 opLogDir    
-rw-rw-r-- 1 xoper sbcprd 9873 Aug 6 00:50 opLogDir
-rw-rw-r-- 1 doper sbcprd 9479 Aug 6 04:12 opLogDir

Now I can select data from it and sort using:

check | awk '{print $3,$8,$6,$7}'| sort

and get the o/p as below,

boper 03:34 Aug 6
doper 04:12 Aug 6
moper 02:18 Aug 6
noper 03:36 Aug 6
soper 03:04 Aug 6
woper 05:06 Aug 6
xoper 00:50 Aug 6

It sorts the o/p by column #1.

How can I sort the o/p according to the timings (column #2)?

2 个答案:

答案 0 :(得分:2)

使用sort命令。 sort -k 2

虽然看起来像ls输出,但您可以更改check以使ls -lt按时间戳排序。

如果您需要更广泛的内容(例如,包括基于日期和时间的排序),那么它就更难了 - 您需要使用可以将时间戳解析为unix时间的内容。

E.g:

#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece; 

my $year = Time::Piece->localtime -> year;

for ( <DATA> ) {
     my ( $mon, $day, $time ) = (split)[5,6,7];
     my $timestamp = Time::Piece->strptime("$mon $day $time $year", '%b %d %H:%M %Y');
     print $timestamp -> epoch,"\n";
}

__DATA__
-rw-rw-r-- 1 noper sbcprd 9175 Aug 6 03:36 opLogDir    
-rw-rw-r-- 1 soper sbcprd 9104 Aug 6 03:04 opLogDir    
-rw-rw-r-- 1 moper sbcprd 9561 Aug 6 02:18 opLogDir    
-rw-rw-r-- 1 woper sbcprd 9561 Aug 6 05:06 opLogDir    
-rw-rw-r-- 1 boper sbcprd 9834 Aug 6 03:34 opLogDir    
-rw-rw-r-- 1 xoper sbcprd 9873 Aug 6 00:50 opLogDir
-rw-rw-r-- 1 doper sbcprd 9479 Aug 6 04:12 opLogDir

或者使用int:

构建排序逻辑
#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece; 

my $year = Time::Piece->localtime -> year;

sub sort_by_timestamp {
    my ( $amon, $aday, $atime ) = (split( " ", $a ))[5,6,7];
    my ( $bmon, $bday, $btime ) = (split( " ", $b ))[5,6,7];
    my $at = Time::Piece->strptime("$amon $aday $atime $year", '%b %d %H:%M %Y');
    my $bt = Time::Piece->strptime("$bmon $bday $btime $year", '%b %d %H:%M %Y');

    return $at <=> $bt;
}


print sort { sort_by_timestamp } <DATA>;

__DATA__
-rw-rw-r-- 1 noper sbcprd 9175 Aug 6 03:36 opLogDir    
-rw-rw-r-- 1 soper sbcprd 9104 Aug 6 03:04 opLogDir    
-rw-rw-r-- 1 moper sbcprd 9561 Aug 6 02:18 opLogDir    
-rw-rw-r-- 1 woper sbcprd 9561 Aug 6 05:06 opLogDir    
-rw-rw-r-- 1 boper sbcprd 9834 Aug 6 03:34 opLogDir    
-rw-rw-r-- 1 xoper sbcprd 9873 Aug 6 00:50 opLogDir
-rw-rw-r-- 1 doper sbcprd 9479 Aug 6 04:12 opLogDir

注意 - 出于显而易见的原因,当你跨越一年时,这不会很好。

答案 1 :(得分:0)

如果您不知道-k选项,您仍然可以将$8放在首位:

awk '{print $8,$3,$6,$7}'