Krupal Patel
Krupal Patel

Reputation: 53

Printing columns in the output file

I got the output for the last command using the below command

last -w -F | awk '{print $1","$3","$5$6$7$8","$11$12$13$14","$15}' | tac | tr ',' '\t'

Now for the same output i want to add the below column names and then copy to csv file or xls file.

Can someone help me out here.

Column Names

USERNAME
HOSTNAME
LOGIN_TIME
LOGOUT_TIME
DURATION

Output looks like this

oracle localhost 2015 2.30
root   localhost 2014 2.30

Appreciate your help on this.

Upvotes: 3

Views: 121

Answers (1)

John1024
John1024

Reputation: 113834

Try this:

last -w -F | awk '{print $1,$3,$5$6$7$8,$11$12$13$14,$15} END{print "USERNAME\tUSERNAME\tHOSTNAME\tHOSTNAME\tLOGIN_TIME\tLOGIN_TIME\tLOGOUT_TIME\tLOGOUT_TIME DURATION"}' OFS='\t' | tac

I added the headings to the END statement in awk. This way, after tac is run, the headings will be at the beginning.

I also set awk's OFS to a tab so that the tr step should no longer be needed.

I couldn't thoroughly test this because my last command apparently produces a different format than yours.

Writing to a file

To write the above output to a file, we use redirection: stdout is sent to a file:

last -w -F | awk '{print $1,$3,$5$6$7$8,$11$12$13$14,$15} END{print "USERNAME\tUSERNAME\tHOSTNAME\tHOSTNAME\tLOGIN_TIME\tLOGIN_TIME\tLOGOUT_TIME\tLOGOUT_TIME DURATION"}' OFS='\t' | tac >new.tsv

The above code produces a tab-separated file. After selecting the options for tab-separated format, Excel should be able to read this file.

If one wants a comma-separated-file, then all we need to to is replace the \t by ,:

last -w -F | awk '{print $1,$3,$5$6$7$8,$11$12$13$14,$15} END{print "USERNAME,USERNAME,HOSTNAME,HOSTNAME,LOGIN_TIME,LOGIN_TIME,LOGOUT_TIME,LOGOUT_TIME DURATION"}' OFS=',' | tac >new.csv

If I recall correctly, one can open this in excel with file->open->text file.

Upvotes: 1

Related Questions