Home bash Delete lines in files of a specific folder recursively earlier than a...

Delete lines in files of a specific folder recursively earlier than a specific date SED, AWK




tell me how to use sed, awk to delete everything older than 7 days recursively in all files, in all / home / * / * .log folders in files.
The file format is:

2018-12-23 23: 34: 43.358 7 INFO
2019-06-12 12: 33: 43.358 7 INFO
2020-05-12 11: 23: 43.358 7 INFO
2020-09-23 10: 34: 43.358 7 INFO

Answer 1, authority 100%

The given answer as such is not a solution and it seems to me that there will hardly be a solution that will fit by sed or awk .
During the execution of the script, all lines that do not start with the date of the format % Y-% m-% d will be deleted from the logs, i.e. if there is a line for today, then a line without a date and again a line for today, the line without a date will still be deleted.
Also, a large date range can cause a runtime error.

# Variable for specifying a period of time, current day +1, i.e. if 6 is specified, then we get 7 days from today
todate = 6
# Since the variable is appended, it is better to clear it
unset datestr
# Loop for forming a string with dates, for further use in the sed command
for ((i = - $ todate; i & lt; = 0; i ++)); do
  if [$ i -eq 0]; then
    datestr + = `date -d" $ i day "+ '^% Y-% m-% d'`
    datestr + = `date -d" $ i day "+ '^% Y-% m-% d \ |'`
# We process all files that match the mask, removing everything from them except for lines where at the beginning there will be lines from the date range created in the loop
sed / "$ datestr" / \! d /home/*/*.log

The -i parameter has been removed in sed, which will overwrite the file, before adding it, it is better to make sure that the command output is correct and does not appear erroneous, the parameter is set immediately after calling sed -i ...

The need to delete logs, as well as optimize storage and more, can be satisfied with the same logrotate , you can read more details on the Internet or run the command man logrotate in the terminal.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions