Linux command line: find files that have been modified

If you want to find out what regular files have been modified in the last ten minutes, you can use the -cmin and -type options of the find command:

    find . -type f -cmin -10

This command line will find regular files that are modified within the last 10 minutes, you can do some operations on them at the same time — suppose you have inadvertently extracted some files from a tar ball in the wrong dir and it’s all a mess, you can clean them up by this magic trick:

    find . -type f -cmin -1 -exec rm {} \;

But what if there are also directories extracted? How can we clean these up? You probably think it’s as easy as this:

    find . -cmin -1 -exec rm {} \;

However, there are some complications here, because in every directory there is a . which points to the dir itself, and a .. which points to its parent, when any file in the dir is modified, the dir is also considered as modified, so the last line would evoke some error like “. and .. can’t be removed”.

No despair, please. We have yet another trick:

    find . -cmin -1 \( -not -iname "." \) -exec rm -rf {} \;

You should be able to clean everything up with this monster.

Notes

  1. Of course there are other shell operators like -and, -or
  2. You can use more than one group of conditions, too, e.g. ( -not
    -iname “.” ) ( -not -iname “readme” )
  3. There is a space after (, and a space before ), this is very
    important
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s