UNIX find: opposite of -newer option exists?

2020-08-09 05:03发布

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.

标签: unix find
6条回答
Rolldiameter
2楼-- · 2020-08-09 05:41

Unfortunately, find doesnt support this ! -newer doesnt mean older. It only means not newer, but it also matches files that have equal modification time. So I rather use

for f in path/files/etc/*; do
    [ $f -ot reference_file ] &&  {
        echo "$f is older" 
        # do something
    }
done
查看更多
家丑人穷心不美
3楼-- · 2020-08-09 05:43

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 '{}' +
查看更多
贪生不怕死
4楼-- · 2020-08-09 05:44

If you only need files that are older than file "foo" and not foo itself, exclude the file by name using negation:

find . ! -newer foo ! -name foo
查看更多
混吃等死
5楼-- · 2020-08-09 05:48
find dir \! -newer fencefile -exec \
  sh -c '
    for f in "$@"; do
      [ "$f" -ot fencefile ] && printf "%s\n" "$f"
    done
  ' sh {} + \
;
查看更多
放我归山
6楼-- · 2020-08-09 05:52

Please note, that the negation of newer means "older or same timestamp":

As you see in this example, the same file is also returned:

thomas@vm1112:/home/thomas/tmp/ touch test
thomas@vm1112:/home/thomas/tmp/ find ./ ! -newer test
./test
查看更多
何必那么认真
7楼-- · 2020-08-09 06:06

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.

查看更多
登录 后发表回答