NoChecksum
NoChecksum

Reputation: 1226

Date output as command-line argument

I'd like to count syslog entries matching a pattern in the last 5 minutes.

I can hardcode a time and get the expected output:

$ awk '$3>"16:20:00"' /var/log/syslog | grep "UFW BLOCK" | wc -l
1502

The desired time can be constructed with:

$ date --date='5 minutes ago' '+%H:%M:%S'
16:00:00

How can I join these in a one-liner?

I tried setting an environment variable, but it returns the entire log. I can't see my error.

$ logdate=`date --date='5 minutes ago' '+%H:%M:%S'` && awk '$3>"$logdate"' /var/log/syslog | grep "UFW BLOCK"

Upvotes: 2

Views: 253

Answers (2)

Scott Dial
Scott Dial

Reputation: 11

Your awk command is single-quoted, which disables the shell's string interpolation. An easy way to check yourself on this type of error is to change awk to echo and see what it says ($3>"$logdate"). If you used double-quotes and escaped the characters appropriately ("\$3>\"$logdate\"", then you would be passing to awk that argument that you intended.

$ logdate=`date --date='5 minutes ago' '+%H:%M:%S'` && awk "\$3>\"$logdate\"" /var/log/syslog | grep "UFW BLOCK"

Upvotes: 1

anubhava
anubhava

Reputation: 784878

You may use:

awk -v dt="$(date --date='5 minutes ago' '+%H:%M:%S')" '$3>dt && /UFW BLOCK/' /var/log/syslog

Note how you can avoid last grep by using awk to do the search pattern as well.

Upvotes: 2

Related Questions