0

I want to withdraw the fourth field of the output of lastlog -u 'user' however using cut -d' ' -f4 I can only withdraw the first field otherwise whitespace is output.

Username         Port     From             Latest
auser            pts/31   c-73-123-11-86.h Sun Jan 19 13:52:08 -0800 2014

I want to remove 'Sun Jan 19 13:52:08'. How can I do this considering there are multiple spaces in the line I want and using cut with specific subscript locations will produce erroneous results when usernames of different length are input. How can I solve this problem?

Whoppa
  • 949
  • 3
  • 13
  • 23
  • See [How to make the 'cut' command treat several sequential delimiters as one?](http://stackoverflow.com/questions/4143252/how-to-make-the-cut-command-treat-several-sequential-delimiters-as-one) – Michael Berkowski Jan 20 '14 at 22:07

3 Answers3

2

I believe this will do what you are asking for

lastlog -u 'user' |  grep -v Latest | awk '{$1="";$2="";$3="";print $0 }'

In your example, this will output

Sun Jan 19 13:52:08 -0800 2014
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

It seems that using any delimiter to separate lastlog output is problematic, since some of the fields may be empty:

ubuntu@ubuntu:~$ lastlog -u ubuntu
Username         Port     From             Latest
ubuntu                                     **Never logged in**
ubuntu@ubuntu:~$ 

Alternatively you can just cut at the right number of characters, though this could be problematic too if the output ever changes in a new version:

ubuntu@ubuntu:~$ lastlog -u ubuntu | { read; cut -c44- ;}
**Never logged in**
ubuntu@ubuntu:~$ 

Note the read simply reads and discards the first/header line of lastlog output.

Digital Trauma
  • 15,475
  • 3
  • 51
  • 83
  • With read, it will remove other records, if this user has several sessions. – BMW Jan 21 '14 at 01:33
  • @BMW - can you elaborate? In this case, there is just one invocation of `read` - no while loops or anything. So exactly one line will be read from stdin of the {} command grouping. Then the remaining lines will be read by `cut`. Or am I missing something? – Digital Trauma Jan 21 '14 at 04:34
0

You could count the length of the lines up to the string Latest and cut at that point:

$ lastlog -u $USER | (
    IFS= read -r line1
    IFS= read -r line2
    length=${#line1}
    echo "${line2::$((length - 6))}"
)

For my user this returns:

abcdef           tty1                      

(I don't have a "From" value for this user)

l0b0
  • 55,365
  • 30
  • 138
  • 223