Home > Software engineering >  Print Date and Username from a secure log file
Print Date and Username from a secure log file

Time:11-24

I'm trying to get the Username and Date 'y/m/d' from a /var/log/secure, however when I'm trying to use awk, it only provides the date.

Sample of a secure log file.

2022-11-23T02:03:24.594880 01:00 servername su: pam_unix(su:session): session opened for user john.doe by (uid=0)

What I'm expecting to print is: 2022-11-23 john.doe

Here's my code.

cat /var/log/secure | grep 'session opened' | awk -FT '{print $1 " " " User: " $9 }'

"The output is only: 2022-11-23 User:"

I'm new to this, so your help will be happy appreciated. Thank you.

CodePudding user response:

You use the T char as the field separator.

That gives you 2 fields where field 1 is 2022-11-23 and after that you print User:


What you might do is use either 1 or more spaces or T as a field separator and then print field 1 and field 10:

 awk -F"[[:blank:]] |T" '{print $1, $10 }' file

Another option could be splitting the first field on T instead of the whole line and then print the first part followed by field 9:

awk '{split($1,a,"T"); print a[1], $9}'

Or matching the date like pattern followed by a T and then print the match without the T followed by field 9:

awk 'match($0, /^[[:digit:]][[:digit:]][[:digit:]][[:digit:]]-[[:digit:]][[:digit:]]-[[:digit:]][[:digit:]]T/) {
  print substr($0,RSTART,RLENGTH-1), $9
}'

Output

2022-11-23 john.doe

CodePudding user response:

With your shown samples please try following awk code.

awk -F'T| user | by '  '{print $1,$3}' Input_file

CodePudding user response:

With the assumption that the date always comes first and the username is in between the strings user and by A sed solution would be something like:

sed '/session opened/s/^\([^T]*\).* user \(.*\) by .*$/\1 \2/' /var/log/secure
  • Related