简体   繁体   English

如何使用 awk 处理最后一个命令的结果?

[英]How to process result of last command with awk?

I have to count how many users were logged in each day of the week.我必须计算一周中每天有多少用户登录。 I can get the data with the last command on the server, but how can I process it with awk?我可以使用服务器上的最后一条命令获取数据,但是如何使用 awk 处理它? It is a long list of data, the name of the day is in the 4th column.这是一长串数据,日期名称在第 4 列。 I declared an array like this: t["Sun"]=0;我声明了一个这样的数组: t["Sun"]=0; t["Sat"]=0; t[“星期六”]=0; etc, I can count it from a simple input from the terminal, but how can I use it on the output of last?等等,我可以从终端的简单输入中计算它,但是如何在最后的 output 上使用它?

If I log in the server and type: last, I get a result like this, each row containing the name of the user, pts/something, ip address, day of the week, time etc:如果我登录服务器并输入:最后,我会得到这样的结果,每一行都包含用户名、pts/something、ip 地址、星期几、时间等:

user pts/0 address Mon etc.

user pts/1 address Wed etc.

I'd like an output like this:我想要一个像这样的 output :

Mon: 10 users were logged in

Tue: 20 user were logged in etc

My code is here, which works with an input from terminal:我的代码在这里,它适用于来自终端的输入:

awk '
        BEGIN { t["Sun"]=0; t["Sat"]=0; t["Fri"]=0; t["Thu"]=0; t["Wed"]=0; t["Tue"]=0; t["Mon"]=0; }
        { t[substr($4,i,3)]++;} 
        END {for(i in t) print i ": " t[i]}   
'$*

So far to an input in terminal like this:到目前为止,终端中的输入如下:

aa ss dd Fri
a d g Mon
q w e Fri

gives the result:给出结果:

Wed: 0
Tue: 0
Fri: 2
Thu: 0
Sat: 0
Sun: 0
Mon: 1

How can I use the awk command to process the output of last?如何使用 awk 命令处理最后的 output?

It sounds like you might want something like:听起来你可能想要这样的东西:

last |
awk '
    BEGIN { split("Sun Mon Tue Wed Thu Fri Sat",days) }
    { numUsers[$4]++ }
    END {
        for (dayNr=1; dayNr in days; dayNr++) {
            dayName = days[dayNr]
            printf "%s: %d users were logged in\n", dayName, numUsers[dayName]
        }
    }
'

so you always get output for every day, including days when no-one logged in, and the days are sorted in the weekday order you prefer.所以你总是得到 output 的每一天,包括没有人登录的日子,这些日子按照你喜欢的工作日顺序排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM