Keep the log for the last 14 days

36 views Asked by At

I'm new to Linux command. I'm currently writing a logic in test.sh to only keep the Example.log for the last 14 days.

Example.log

[2024-03-25 05:36:42]: ERROR No such file or directory
[2024-03-24 05:36:42]: ERROR No such file or directory
[2024-03-23 05:36:42]: ERROR No such file or directory
[2024-03-21 05:36:42]: ERROR No such file or directory
[2024-03-20 05:36:42]: ERROR No such file or directory
[2024-03-19 05:36:42]: ERROR No such file or directory
[2024-03-18 05:36:42]: ERROR No such file or directory
[2024-03-17 05:36:42]: ERROR No such file or directory
[2024-03-16 05:36:42]: ERROR No such file or directory
[2024-03-15 05:36:42]: ERROR No such file or directory
[2024-03-14 05:36:42]: ERROR No such file or directory
[2024-03-13 05:36:42]: ERROR No such file or directory
[2024-03-12 05:36:42]: ERROR No such file or directory
[2024-03-11 05:36:42]: ERROR No such file or directory

My first thought is to use awk with if to fetch each line, then use cut to get the first 10 characters and compare to current day. If not in 14 days, then delete it. But I'm not sure how to convert this logic to Linux command.

Your help is much appreciated.

Thanks!

1

There are 1 answers

1
ufopilot On BEST ANSWER
$ awk -F'^.|-| ' -v date=$(date +%Y%m%d) '$2$3$4 >= date-14' logfile
[2024-03-25 05:36:42]: ERROR No such file or directory
[2024-03-24 05:36:42]: ERROR No such file or directory
[2024-03-23 05:36:42]: ERROR No such file or directory
[2024-03-21 05:36:42]: ERROR No such file or directory
[2024-03-20 05:36:42]: ERROR No such file or directory
[2024-03-19 05:36:42]: ERROR No such file or directory
[2024-03-18 05:36:42]: ERROR No such file or directory
[2024-03-17 05:36:42]: ERROR No such file or directory
[2024-03-16 05:36:42]: ERROR No such file or directory
[2024-03-15 05:36:42]: ERROR No such file or directory

or

$ awk -F'^.|-| ' -v date=$(date +%Y%m%d) '$2$3$4 < date-14{exit}1' logfile