English 中文(简体)
Bash edit file and keep last 500 lines
原标题:

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.

最佳回答

Think about using logrotate.
It will not do what you want (delete all lines but the last 500), but it can take care of logfiles which are bigger than a certain size (normally by comressing the old ones and deleting them at some point). Should be widely available.

问题回答

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

In my opinion the easiest and fastest way is using a variable:

LASTDATA=$(tail -n 500 filename)
echo "${LASTDATA}" > filename
DIR=/path/to/my/dir # log directory
TMP=/tmp/tmp.log # temporary file
for f in `find ${DIR} -type f -depth 1 -name *.log` ; do
  tail -n 500 $f > /tmp/tmp.log
  mv /tmp/tmp.log $f
done

In bash you loop over files in a directory, e.g. like this:

cd target/directory

for filename in *log; do
    echo "Cutting file $filename"
    tail -n 500 $filename > $filename.cut
    mv $filename.cut $filename
done




相关问题
Best logging approach for composite app?

I am creating a Composite WPF (Prism) app with several different projects (Shell, modules, and so on). I am getting ready to implement logging, using Log4Net. It seems there are two ways to set up the ...

How to make logging.debug work on Appengine?

I m having a tough time getting the logging on Appengine working. the statement import logging is flagged as an unrecognized import in my PyDev Appengine project. I suspected that this was just an ...

How to validate Java logging properties files?

I have a basic facility for allowing users to remotely apply changes to the logging files in my application. Some logs are configured using java.util.logging properties files, and some are configured ...

Logging SAS scripts

I ve been developing a lot of Java, PHP and Python. All of which offer great logging packages (Log4J, Log or logging respectively). This is a great help when debugging applications. Especially if the ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

热门标签