I would like to monitor the /var/log/secure file for user activity. I need to be able to provide a start date and select lines only occurring after that date . I have played around with awk for a while and have not been able to find a solution that works. I have had some commands that appear to work but just end up selecting every line from the file. In the command below I am trying to select all entries after July 9th, 2019.

cat /var/log/secure* | awk '{d=system("date -d "$1 $2, 2019 $3" +%s"); if ( 1562731201 < d );  print}'
awk: cmd. line:1: {d=system("date -d "$1 $2, 2019 $3" +%s"); if ( 1562731201 > d );  print}
awk: cmd. line:1:                                         ^ 2 is invalid as number of arguments for system

date -d @1562644801
Tue Jul  9 00:00:01 EDT 2019

Any help you can provide would be appreciated.

  • If you use GNU awk, then use its builtin mktime() function instead of calling out to date for every line. Should be a lot faster, but you make have to do a little more work to build the string argument for mktime. – glenn jackman Jul 11 at 14:37

I believe Below command may work, As tested it worked fine for me

sed -n '/Jul 9 [0-9]\{2\}:/,$p' /var/log/secure| sed '/Jul 9 [0-9]\{2\}:/d'
  • Sorry for the delay in my response Praveen, I appreciate your answer. If you are willing and have time can you please explain what this command is actually doing? – Paul Jul 23 at 20:17
  • It will select all lines after July 9 2019 till last line tested and worked too – Praveen Kumar BS Jul 23 at 23:39

You need to escape the inner quotation marks.

"date -d \"$1 $2, 2019 $3\" +%s"

So turn it into

'{d=system("date -d \"$1 $2, 2019 $3\" +%s"); if ( 1562731201 < d );  print}'
  • Thanks for the quick reply Panki. looks like the date command is not accepting the parameters passed to it and it is printing entries before July 9. date: invalid date ‘ , 2019 ’ Jul 8 01:44:32 server1 sshd[34408]: pam_unix(sshd:session): session opened for user root by (uid=0) – Paul Jul 11 at 14:33
  • Assuming $1,$2,$3 are awk fields, they can't be inside a quoted string: cmd=sprintf("date -d \"%s %s, 2019 %s\" +%%s", $1, $2, $3), d = system(cmd) – glenn jackman Jul 11 at 14:33
  • @glennjackman Post this as an answer if it ends up working for OP – Panki Jul 11 at 14:36
  • Feel free to put it in your answer. – glenn jackman Jul 11 at 14:38
  • cat /var/log/secure* | awk '{cmd=sprintf("date -d \"%s %s, 2019 %s\" +%%s", $1, $2, $3), d = system(cmd); if ( 1562731201 < d ); print}' gives a syntax error on this comma before the d "......$3), d = system(cmd)....." if I change it to a semicolon it selects entries before July 9th. – Paul Jul 11 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.