How to truncate multiple log files at once and leave only last N number of lines in it?

639 views Asked by At

I have two commands that I usually use to truncate log files but the issue is the first one will completely truncate it and the second one works only on one file at the time.

  1. find /path/to/log/directory -name *log -exec cp /dev/null '{}' \;
  2. echo "$(tail -1000 /home/username/public_html/error_log)" > /home/username/public_html/error_log

I need command that will work on multiple log files at once and truncate it so that last 1000 lines will stay in those log files.

Thanks :cheers:

1

There are 1 answers

0
3fxcf9 On

A simple command for doing this should be:

for file in *.log; do [[ -f "$file" ]] && echo "$(tail -n 1000 "$file")" > "$file"; done

This command searches for all .log files in the current directory and truncates them by keeping only the last 1000 lines.