简体   繁体   English

使用 sed 打印每个匹配模式的第一行出现

[英]Print the first line occurrence of each matching pattern with sed

I would like to filter the output of the utility last based on a variable set of usernames.我想最后根据一组可变的用户名过滤实用程序的输出。

This is sample output from last unfiltered,这是上次未过滤的样本输出,

reboot   system boot  server   Wed Apr  6 13:15 - 14:24  (01:09)    
user1    pts/0        server   Wed Apr  6 13:08 - 13:15  (00:06)    
reboot   system boot  system   Wed Apr  6 13:08 - 13:15  (00:06)    
user1    pts/0        server   Wed Apr  6 13:06 - down   (00:01)    
reboot   system boot  system   Wed Apr  6 13:06 - 13:07  (00:01)    
user1    pts/0        server   Wed Apr  6 12:59 - down   (00:06)  

What I would like to do is pipe the output of last to sed.我想做的是将 last 的输出通过管道传输到 sed。 Then, using sed I would print the first occurrence of each specified user name ie their last log entry in wtmp.然后,使用 sed 我将打印每个指定用户名的第一次出现,即它们在 wtmp 中的最后一个日志条目。 The output should appear as so,输出应如下所示,

 reboot   system boot  server   Wed Apr  6 13:15 - 14:24  (01:09)    
 user1    pts/0        server   Wed Apr  6 13:08 - 13:15  (00:06)

The sed expression that I particularly like is,我特别喜欢的sed表达式是,

last|sed '/user1/{p;q;}'

Unfortunately this only gives me the ability to match the first occurrence of one username.不幸的是,这只使我能够匹配一个用户名的第一次出现。 Using this syntax is there a way I could specify a multiple of usernames?使用这种语法有没有办法指定多个用户名? Thanks in advance!提前致谢!

awk is better fit here than sed due to awk's ability to use associative arrays: awk这里更适合比sed由于awk的使用关联数组的能力:

last | awk '!seen[$1]++'

reboot   system boot  server   Wed Apr  6 13:15 - 14:24  (01:09)
user1    pts/0        server   Wed Apr  6 13:08 - 13:15  (00:06)

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

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