[root@dwh1 log]# who
dwetl pts/0 2015-03-05 16:29 (10.130.136.56)
dwetl pts/1 2014-12-12 20:41 (10.129.133.154)
dwetl pts/2 2015-03-09 15:57 (10.129.224.28)
root pts/3 2015-03-10 15:28 (10.129.254.46)
dwetl pts/4 2015-03-05 16:42 (10.130.136.56)
root pts/6 2015-03-10 16:35 (10.129.254.46)
dwetl pts/8 2015-03-05 23:05 (10.130.136.56)
[root@dwh1 log]# who | awk '{print $1}' | awk '{a[$1]++}END{for (i in a) print i,a[i]}'
root 2
dwetl 5
perl 版本:
[oracle@dwh1 perl]$ cat a3.pl
#!/usr/bin/perl
###创建一个局部散列数组%who,用来保存登陆到系统的用户和他们的登陆次数的集合
my %who;
open (FH,"who | ") or die;
while (<FH>) {
##S+ 匹配非空格
next unless /^(S+)/;
##第一个模式
print "$1 is $1
";
$who {$1}++;
}
foreach (sort {$who{$b}<=>$who{$a}}keys %who){
print "$_---$who{$_}
";
}
[oracle@dwh1 perl]$ perl a3.pl
$1 is dwetl
$1 is dwetl
$1 is dwetl
$1 is root
$1 is dwetl
$1 is root
$1 is dwetl
dwetl---5
root---2
我们使用一个模式匹配来提取用户名,我们将名字记录到%who散列数组中,并使用户名成为关键字,
每一个用户登陆系统的次数成为值。