Perl & AWK


(0 comments)

The requirements of text manipulation are as follows: Output the information that the users have logged in. The report summarizes each user on a line, including the user name, total login time and number of logins.
Both Perl and AWK programs are designed with the same algorithm diagram: Accumulate the time of login and the number of logins for each user. Each username is a key to access key -> value to their data. These keys are sorted to present output in that order. The input is taken frorm the output of the 'last' command. Suppose every login period does not exceed 24 hours



Using Perl
You compose a source file named login.pl with the following content:


while ( <> ) {
if ( /^(\S+).+\((\d{2}):(\d{2})\)$/ ) {

next if $1 eq "reboot";
$hours{ $1 } += $2;
$minutes{ $1 } += $3;
$logins{ $1 } ++;
}
}

foreach $user ( sort ( keys %hours ) ) {
$hours{ $user } += int ( $minutes{ $user } / 60 );
$minutes{ $user } %= 60;
print "User $user: total login time ";
printf "%02d:%02d, ", $hours{ $user }, $minutes{ $user };
print "total logins $logins{ $user }.\n";
}

Run the program:


last | perl login.pl



Using AWK
You compose a source file named login.awk with the following content:


/^\S+.+\([0-9]{2}:[0-9]{2}\)$/ {
if ( $1 == "reboot" )
next
gsub ( "[()]", "", $NF )
split ( $NF, a, ":" )
hours[$1] += a[1]
minutes[$1] += a[2]
logins[$1] ++
}

END {
asorti ( hours, d )
for ( i in d ) {
user = d[i]
hours[user] += int ( minutes[user] / 60 )
minutes[user] %= 60

printf "User %s: total login time ", user
printf "%02d:%02d, ", hours[user], minutes[user]
print "total logins "logins[user]"."
}

}

Run the program:


last | awk -f login.awk



Currently unrated

Comments

There are currently no comments

New Comment

required

required (not published)

optional

required