0

So i was trying to get X last logins for ALL users using a bash script but does anyone know how exactly to extract only a date so i can create a set in some sort of a table? using last i get output like this:

yogi     pts/0        192.168.0.103    Fri Nov 18 07:04 - 07:05  (00:00)
yogi     pts/1        10.8.3.6         Thu Nov 17 14:36 - 16:53  (02:17)
yogi     pts/0        10.8.3.6         Thu Nov 17 14:32 - 16:45  (02:12)

and so with awk '{print $1, $4, $5, $6,}' i can only go that far but is there away to get something like this:

name surname login date1 date2 date3 date4 etc.

Scratching my head around this for a while now ;/

migrated from stackoverflow.com Nov 27 '16 at 10:11

This question came from our site for professional and enthusiast programmers.

  • Assuming that you are using the last command to extract this data, where do you suppose the name and surname fields are going to come from? – Rolf of Saxony Nov 19 '16 at 15:04
  • @RolfofSaxony Fifth field in /etc/passwd? – James Brown Nov 19 '16 at 15:20
  • aye, that is where i was looking for, as far as i remember there is one field on which I'd have to run some awk magic again but that's the place to look :) – YoGi Nov 19 '16 at 18:54
1

In Gnu awk:

$ cat program.awk
NR==FNR {
    split($5,a,",")
    b[$1]=a[1]
    next
} 
($1 in b) && ++c[$1]<=5 {
    d[$1]=d[$1] $4 " " $5 " " $6 (c[$1]==5?"":OFS)
} 
END {
    for (i in d) 
        print b[i], i, d[i]
}

Run it:

awk -f program.awk OFS=", " FS=":" /etc/passwd FS=" +" <(last)
James Brown, james, Sat Nov 19, Wed Nov 16, Tue Nov 15, Mon Nov 14, Sun Nov 13

Bad example since I'm on my laptop. The order of output is Gnu awk default ie. random. If change the for traverse order with PROCINFO["sorted_in"]="@ind_str_asc" if desired.

  • I was thinking about something that would prevent console from spitting to many lines. With 5 last logins for each user I'm trying to have each user only apear in a single line. So we could have something like this: name1 surname1 login1 date1 date2 date3 date4 date5 name2 surname2 login2 date1 date2 date3 date4 date5 – YoGi Nov 19 '16 at 19:18
  • @YoGi Apparently I lost my thought while coding the previous solution. Is this more like it? – James Brown Nov 19 '16 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy