Reputation: 31
I have a file which has a date at the beginning of each line. I want to get all lines which has a date that is less than the current date.
Here is what I have,
When I used this:
awk '$NF < "2020-10-27"' expiry.txt >sample.txt
I was able to get a desired output
But when I substitute the date above "2020-10-27" to date today , I got no result
My script:
date=$(date '+%Y-%m-%d')
awk '$NF < "$date"' expiry.txt
sample logs in the file
2020-05-30: /tmp/abcd
2019-08-21: /tmp/abcde
2020-03-22: /tmp/abcdef
Thanks
Upvotes: 3
Views: 1164
Reputation: 246807
The problem with your code: the shell will not substitute the $date
variable if it's within single quotes. So you are comparing the date in column 1 against the literal string "$date"
. And because the ASCII value of $
is smaller than the ASCII value of 2
, the $1 value is always lexically greater than the string "$date"
. Hence, no output.
If you have GNU awk, you can use the builtin time functions
gawk '
BEGIN {today = strftime("%Y-%m-%d", systime())}
$1 < today
' Input_file
Upvotes: 2
Reputation: 133518
Based on your shown samples and attempts, could you please try following.
awk -v dat="$(date '+%Y-%m-%d')" -F':' '$1<dat' Input_file
Multiple fixes in OP's attempts:
awk
code.$NF
which is last field of line but as per sample date is coming in very first field of lines, so changed it to $1
(first field).awk
), to catch the exact date and make it first field I have made field separator as :
so that only date value is picked up for match with dat
variable.Upvotes: 3