Get List of All Lines within the date range

Viewed 303

I have a log file with entries like this:

24/09/20 | 11:22:56am | Server1  | Backup Done
28/09/20 | 10:44:05am | Server1  | Error in Config File
10/10/20 | 04:22:10am | Server1  | Error in Config File

How can I extract only the lines which are between

[Today's Date] <-> [Today's Date - 30Days]

After searching on web I found this command to work but it gives a error.

sed -n "/$(date --date='-30 day' '+%d/%m/%y')/,/$(date +'%d/%m/%y')/p"

Error

cat logs.txt | sed -n "/$(date --date='-10 day' '+%d/%m/%y')/,/$(date '+%d/%m/%y')/p"
sed: -e expression #1, char 5: unknown command: `1'

Can anyone please help me to extract only lines which are 30 days old from current date.

1 Answers

Use GNU date to get the date for 30 days ago.

Then reverse the format, to %y%m%d, in order to apply alphabetical comparison with awk.

start=$(date --date='30 days ago' +'%y%m%d')
awk -v start="$start" '{split($1, a, "/")} a[3]a[2]a[1] >= start' file

Note: In general, date formats that can be directly sorted or compared, as strings, like the ISO 8601 date, or as numbers, like the Unix timestamp, should be preferred for timestamped files.

Related