Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNIX find: opposite of -newer option exists?

Tags:

find

unix

I know there is this option for unix's find command:

find -version
GNU find version 4.1

    -newer file Compares the modification date of the found file with that of
        the file given. This matches if someone has modified the found
        file more recently than file.

Is there an option that will let me find files that are older than a certain file. I would like to delete all files from a directory for cleanup. So, an alternative where I would find all files older than N days would do the job too.

like image 672
Ivan Avatar asked Jun 30 '11 15:06

Ivan


People also ask

What is opposite of grep?

To invert the Grep output , use the -v flag.

What does Z do in shell?

The Z shell (Zsh) is a Unix shell that can be used as an interactive login shell and as a command interpreter for shell scripting. Zsh is an extended Bourne shell with many improvements, including some features of Bash, ksh, and tcsh.

What is $# in shell script?

The special character $# stores the total number of arguments. We also have $@ and $* as wildcard characters which are used to denote all the arguments. We use $$ to find the process ID of the current shell script, while $? can be used to print the exit code for our script.

What is +1 in find command?

Similarly +1 will find files modified more than one day ago.


2 Answers

You can use a ! to negate the -newer operation like this:

find . \! -newer filename 

If you want to find files that were last modified more then 7 days ago use:

find . -mtime +7 

UPDATE:

To avoid matching on the file you are comparing against use the following:

find . \! -newer filename \! -samefile filename 

UPDATE2 (several years later):

The following is more complicated, but does do a strictly older than match. It uses -exec and test -ot to test each file against the comparison file. The second -exec is only executed if the first one (the test) succeeds. Remove the echo to actually remove the files.

find . -type f -exec test '{}' -ot filename \; -a -exec echo rm -f '{}' + 
like image 118
qbert220 Avatar answered Oct 08 '22 03:10

qbert220


You can just use negation:

find ... \! -newer <reference>

You might also try the -mtime/-atime/-ctime/-Btime family of options. I don't immediately remember how they work, but they might be useful in this situation.

Beware of deleting files from a find operation, especially one running as root; there are a whole bunch of ways an unprivileged, malicious process on the same system can trick it into deleting things you didn't want deleted. I strongly recommend you read the entire "Deleting Files" section of the GNU find manual.

like image 24
zwol Avatar answered Oct 08 '22 01:10

zwol