Sort current logged in users by log in time (supposedly to be very easy but I'm missing something)

  1. The problem statement, all variables and given/known data:

Show all users who are currently logged in, sorted from earliest to latest log in time. The log in time includes the month, day, and time.

  1. Relevant commands, code, scripts, algorithms:

finger, who, sort, pipe, head, tail,

  1. The attempts at a solution (include all code and scripts):
finger | tail -n +2 | sort -n +4 -5

I've also tried

finger | tail -n +2 | sort -M | sort +6 -7

(thinking that maybe column 7 is the time if you count Dec is 5th column, the 9th is 6th (see the output finger below)

  1. Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):
    De Anza College, Cupertino (California), US, Clare Nguyen, CIS 18A (It won't let me post link because I don't have 5 posts yet)

This is an introductory class to Unix.

Any help would be much appreciated.

Here is an approach using awk that I wrote:-

finger |\
awk ' NR==1 {
  ind=index($0,"Login Time");
 } NR>1 {
  ldt=substr($0,ind,12);
  cmd="date -d \""ldt"\" +%s";
  while ((cmd | getline epoch ) > 0 ) {
   epoch=epoch;
  }
  close(cmd);
  printf "%s %s\n", epoch, $0;
} ' | sort -n | cut -c 12-

Actually I am converting the login time to epoch and performing the sort. You can try doing the same in shell script. I hope this helps.

Hi bipinajith,
Thanks for the answer but it's too advance. Awk was not taught in this course :frowning:

Ok, here is a bash example. You might have to adjust the highlighted sub-string index and length according to your finger output.

#!/bin/bash

rm -f tmp

finger | while read line
do
        if [ $( echo $line | grep -c "^Login" ) -eq 0 ]
        then
                echo "$( date -d"${line:39:12}" +"%s" ) $line" >> tmp
        fi
done

sort -n tmp | cut -c 12-

It's supposed to be just one single line command. We can use pipe. Can you think more simple? haha. I'm sorry but this is just an introductory class to Unix.

How about w:

w | tail -n +3 | sort -k4n

bipinajith,
We're almost there but the problem is w doesn't show the month and date.

finger does. Let's us start with something like this

finger | tail -n +2 | sort -n +4 -5

This is due tomorrow so if you can help me, I'd be greatly appreciated.

Let me explain the problem with using finger, since finger is showing abbreviated month, we cannot apply a numeric or alphabetical order sort on the date. This is the reason why I suggested to convert the date to epoch and perform the sort.

1 Like

Hey, I solved it myself. Finally. I overly complicated the matter

 who | sort -M | sort +3 -4 +4 -5

Thanks for your help.