Friday, 29 March 2013

Useful Find command examples in UNIX

Find command is one of the most useful commands in UNIX, as there are many options out there to accomplish various search tasks.

  • Find files which have been modified for more than or less than a certain time
  • We can use 'find * -mtime n' to search files under current directory based on modification time. The numeric argument n can be specified as +n, meaning greater than n days; -n, meaning less than n days; or n, meaning exactly n days. For example,
    to find files which were last modified for more than 30 days ago
    find . -mtime +30
    to find files which were last modified for less than 15 days ago
    find . -mtime -15
    to find files which were last modified for exactly 10 days ago
    find . -mtime 10
    There are other options like
    -mmin n, which refers to file's data was last modified n minutes ago
    -amin n, which refers to file's data was last accessed n minutes ago
    -atime n, which refers to file's data was last accessed n days ago
    -type f, which searches for regular file
    -type d, which searches for directory,
    -exec command, which executes command by passing in the find results,
    -perm /mode, which searches files with given permission 
    
  • Remove files which are older than n days
  • Since we understand how to search for files which were last modified for more than n days, we can then use the rm command to remove them
    find /some-dir/* -mtimes +30 -type f -exec rm {} \;
    
    '-exec' is used to pass in commands like 'rm'; '{}' is replaced by the file name that 'find' returns; and the '-exec' command has to end with '\;'.
    Another way will be
    find /some-dir/* -mtimes +30 -type f -print0 | xargs -0 rm
    where 'xargs' reads 'find' results and execute 'rm' on each of the 'find' results
  • Find files which contain particular strings
  • Below is an example to search all txt files starting from current directory for string "some-string"
    find . -name "*.txt" -print | xargs grep "some-string"
    

No comments:

Post a Comment