Linux Find and Zip Files

findgziplinux

I'm running into 2 problems when working with my logs and the find command.

  1. I am having problems with the mtime option. The 1st command below shows me a few files from March 5th till March 7th, like I believe it should. However, when I add +1 to mtime instead of +0, it only does an ls of the current directory I'm in when running the command. It's just listening my directories under /home/user/. Not sure why +1 is breaking it.
sudo find /logs/ -type f -name '*.log' -mtime +0 | xargs ls -l
  1. The second issue I'm running into is I want to find all logs that are older than 1 day and zip them up individually. So if my find command finds 1-1-13.log, 1-2-13.log, and 1-3-13.log, I want each one to be turned into log.gz. I tried this by doing the following command but it isn't working. I assume I may have to do a small bash script for this but was hoping to do it by one quick command.

sudo find /logs/ -type f -name '*.log' -mtime +0 | xargs gzip -9 *

Most of the examples I've seen involve zipping all files into 1 archive but I want each one individual and I want them to stay in the same location where it found them.

Thanks in advance.

Best Answer

However, when I add +1 to mtime instead of +0, it only does an ls of the current directory I'm in when running the command.

Your xargs command in this example is weird:

sudo find /logs/ -type f -name '*.log' -mtime +0 | xargs ls -l

If you want to list the files, just use find by itself, e.g:

sudo find /logs/ -type f -name '*.log' -mtime +0

Or:

sudo find /logs/ -type f -name '*.log' -mtime +1

If that command produces the list of files you expect, the next step should be easy (below). If that find command does not produce the list of files you expect, it suggests that those files have actually been modified more recently than you think.

The second issue I'm running into is I want to find all logs that are older than 1 day and zip them up individually. So if my find command finds 1-1-13.log, 1-2-13.log, and 1-3-13.log, I want each one to be turned into log.gz.

You have a problem with your xargs command:

sudo find /logs/ -type f -name '*.log' -mtime +0 | xargs gzip -9 *

You need to get rid of that * in your xargs command; you expect the list of files passed to gzip to come from the find command, rather than via shell globbing. So this should work just fine:

find /logs -type f -name '*.log' | xargs gzip -9

You could also do this using find ... -exec ..., but this is typically a less performant solution.