Digital Marketing

How to find and process files depends on modify days on Linux

find /path/to/files/* -mtime +88 -exec rm {} \;

or

find /path/to/files/* -mtime +88 -exec rm -f {} \;  (with the confirm parameter)

To avoid accidental problem, it is better run

find /path/to/files/* -mtime +88

first to make sure they are the files you are going to delete.

The second argument, -mtime, is used to specify the number of days old that the file is. If you enter +88, it will find files older than 88 days.
The third argument, -exec, allows you to pass in a command such as rm. The  \; at the end is required to end the command.

If you want to process files newer than 88 days, you can instead do the following:

find /path/to/files/* -mtime -88

Following example finds all the files under root file system that changed within the last 24 hours:
find / -ctime -1 > /tmp/changed-file-list.txt &

See also: 

If you want to copy files newer than 88 days to another folder:

find /path/to/files/* -mtime -88 -exec cp -f {} /path/to/another/folder/ \;

If there are too many files and you get Argument list too long error,
(
See also How to fix: find: Argument list too long
)
you can try to solve it by cd-ing to that path first

cd /path/to/files/
find . -mtime -88 -exec cp -f {} /path/to/another/folder/ \;

Or you can use -delete action directly:

find /path/to/files/* -mtime +88 -delete

If you will be executing over many results, it is more efficient to pipe the results to the xargs command instead. xargs is a more modern implementation, and handles long lists in a more intelligent way. The print0 option can be used with this.

The following command will ensure that filenames with whitespaces are passed to the executed COMMAND without being split up by the shell. It looks complicated at first glance, but is widely used.

find . -print0 | xargs -0 COMMAND ( good for Argument list too long error)

Example:


find /pmta/inbound/ -name "*.msg" -mtime 2 -type f -print0 | xargs -0 rm -f

For safety you can pipe the output from find to something like awk and create a batch file with each line being "rm filename"

That way you can check it before actually running it and manually fix any odd edge cases because of murphy's law:
$ sudo find /home/ -name  "*.csv" -type f | grep processed | awk '{print "sudo rm -f "$1}'  > /tmp/letsdoit.sh
$ sudo find /home/ -name "*.xml" -type f -mtime +7 | grep problem | awk '{print "sudo rm -f "$1}' >> /tmp/letsdoit.sh

Comments

Popular posts from this blog

Make online money from the Internet