Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Date and Username from a secure log file

Tags:

bash

awk

rhel

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:"

like image 507
MMonteza Avatar asked Nov 30 '25 11:11

MMonteza


2 Answers

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, /^[0-9]{4}(-[0-9]{2}){2}T/) {
  print substr($0,RSTART,RLENGTH-1), $9
}'

Output

2022-11-23 john.doe
like image 136
The fourth bird Avatar answered Dec 03 '25 12:12

The fourth bird


With your shown samples please try following awk code.

awk -F'T| user | by '  '{print $1,$3}' Input_file
like image 37
RavinderSingh13 Avatar answered Dec 03 '25 14:12

RavinderSingh13