user3590575
user3590575

Reputation: 21

Unix awk script: print the total dates investigated from file

I need to search a file that has the number of people who logged in each date, their username and the time logged in. The last printout of the run is to contain the total dates investigated. The script must be in either awk, sed or grep. The output is supposed to look like this:

Oct 5 :===: 4
joesag    20:50
heidi3    17:42
jlandis   15:53
dskahnkar 21:51

this line will change depending on the number of dates the script finds. The file I'm working with only has 3 different dates the 5, 6, and 7th. The total number of dates investigated is 3

This is my code so far:

awk 'BEGIN{print "Oct 5 :===:"}; $4 ~ /5/{print $1, $5}' whotb
echo
awk 'BEGIN{print "Oct 6 :===:"}; $4 ~ /6/{print $1, $5}' whotb
echo
awk 'BEGIN{print "Oct 7 :===:"}; $4 ~/7/{print $1, $5}' whotb

This is what it prints out:

Oct 5 :===: 
jlandis 15:53 
dshankar 21:51 
heidi3 17:42 
revans 19:30
shawj 13:51 
axkrk 17:15 
emgarcia 13:31 
joesag 20:50

Oct 6 :===: 
hinze 12:17 
natasha 12:57 
lestrat 22:17 
eyora 18:46
hoythill 15:00 
wkb13 15:03 
wolves24 08:53 
fonstad 21:48 
joseher 18:08


Oct 7 :===: 
gelderen 05:52 
bwood3 04:43 
atsxc 05:40 
jaquez 05:48
jondrnj 05:50 
ash786 00:39 
yiyun827 01:07

The input file has 27 of lines:

gelderen pts/0 Oct 7 05:52 (egelderen-c217.la.asu.edu)

bwood3 pts/1 Oct 7 04:43 (ss1-04.inre.asu.edu)

Upvotes: 1

Views: 189

Answers (2)

jaypal singh
jaypal singh

Reputation: 77105

The counter variable you put in the END block will do nothing since END block is ran after the file has been processed.

I would recommend to create different arrays (depending on dates) and push the pairs in it as keys. Since you mention that file only has three dates, you can create three arrays and iterate them in the END block.

awk '
BEGIN { SUBSEP = FS }
$4==5 { fifth[$1,$5]++ }
$4==6 { sixth[$1,$5]++ }
$4==7 { seventh[$1,$5]++ }
END {
    print "Oct 5 :===: ", length(fifth); for(pair in fifth) print pair
    print "Oct 6 :===: ", length(sixth); for(pair in sixth) print pair
    print "Oct 7 :===: ", length(seventh); for(pair in seventh) print pair
}' whotb

Upvotes: 1

Håkon Hægland
Håkon Hægland

Reputation: 40758

You can try the following perl script:

#! /usr/bin/perl

use v5.12;

my %info;

while (<>) {
    my @fld=split(" ");
    my $key=join(" ",@fld[2..3]);
    if (!defined $info{$key}) {
        $info{$key}={num => 0, users => []};
    }
    $info{$key}->{num}++;
    my $user=join(" ",@fld[0,4]);
    push( @{$info{$key}->{users}}, $user);
}

for my $key (sort keys %info) {
    say $key,":===:",$info{$key}->{num};
    say $_ for (@{$info{$key}->{users}});
    say "";
}

Run it as ./p.pl whotb

Upvotes: 0

Related Questions