用linux shell命令find查找哪些文件曾经在x天/x小时/x分钟内被修改过

我们经常会用到如何知道哪些文件曾经在几天或几小时或几分钟内被修改过,那么find命令就可以很好的来完成查找任务。以下将详细地进行介绍:

The basic syntax of the find command is:

find path options

where path is the path to search
and options are the options given to find command. In all our below examples, the path is our current directory and hence we use .(dot).

1. To find files modified in the last 5 days:

find . -mtime -5

2. To find files modified before 5 days:

find . -mtime +5

 Note: Developers, be aware. + is not default in find. If you omit the ‘+’, it has a different meaning. It means to find files modified exactly before 5 days.

3. To find files modified in the last 40mins:

find . -mmin -40

4. To find files modified before 40mins:

find . -mmin +40

The above commands will find both files and directories modifying the criteria. If you want to find only files, use the -type option.

find . -type f -mmin -40

 This will find only the files modified in the last 40 mins, not directories.5. By the way,  not in all Unix flavours one will find the -mmin option. If you dont have the mmin option, use the following:

First create a dummy file whose timestamp is the time you are looking for:

touch -d "40 mins ago" temp

  The above touch command will create a temp file whose timstamp is 40mins before. For example, if the time now is 10hours 50mins, the temp file timstamp will be 10hours 40mins.If your Unix flavor does not have the “-d” option in the touch command, you can use the following method to set the timestamp:

touch -t 1008211020 temp

   This creates a temp file whose time stamp is 2010,Aug 21, 10hours 20mins. [YYMMDDHHMM]Second, search files which are modified after this file temp has been modified. The below command will display all the files modified after the temp has been modified OR in other words find files which are newer than temp file:

find . -newer temp

Similarly, to find files which are modified before 40 mins. In other words to negate the above search, use the exclamation:

find . ! -newer temp

In the same way,  we can find files modified from any time we need.6. One of the frequent requirement a sys admin gets is to find files modified before say last 2 days and 10 hours 30mins and move them to a backup directory. It can be achieved by the below commands:

#touch -d "2days 10 hours 30  mins ago" temp
#find / -type f ! -newer temp -exec mv '{}' ~/backup \;

The above example does 2 things:a. First create a temp file whose timstamp is 2 days 10 hours and 30mins ago.b. Finds all the files under root which are older than the temp file and moves them to the backup directory.  The same thing using “touch -t” will be like assuming todays date is 21 Aug 2010, 15hours,45mins:

#touch -t 1008190515 temp
#find / -type f ! -newer temp -exec mv '{}' ~/backup \;

   1008190715 indicates 2010(10), Aug(08), 19th(19), 5 hours(05) and 15mins.