Bash edit file and keep last 500 lines

Lizard picture Lizard · May 21, 2010 · Viewed 7.9k times · Source

I am looking to create a cron job that opens a directory loops through all the logs i have created and deletes all lines but keep the last 500 for example.

I was thinking of something along the lines of

tail -n 500 filename > filename

Would this work?

I also not sure how to loop through a directory in bash.

Answer

user2553977 picture user2553977 · Jul 5, 2013

If log file to be truncated is currently open by some services, then using mv as in previous answers will disrupt those services. This can be easily overcome by using cat instead:

tail -n 1000 myfile.log > myfile.tmp
cat myfile.tmp > myfile.log