6.3.7 Usage of find command

It is very convenient to search for files and folders on the command line using the find command

  • Search files by name:
  1. find /var/www/ -name "file.conf"
  2. find /var/www/ -name "*.conf"
  • Case insensitive search:
  1. find /var/www/ -iname file.conf
  • Search by file size:
  1. find /home/user -size +10M
  • Search by rights mask:
  1. find ./ -perm 700
  • Search by date for files created or modified within the last 5 days:
  1. find /home/user -type f -mtime -5
  • Files created or modified within the last 5 minutes:
  1. find /home/user -type f -mmin -5
  • Find files created or modified older than 30 days (aka search for outdated files):
  1. find /path -type f -mtime +30
  • Delete files created or modified older than 30 days:
  1. find /path -type f -mtime +30 -delete
  • Time of last call for which is more than 5 days:
  1. find /usr/bin -type f -atime +5
  • Search for a string in files:
  1. find ./ -type f -exec grep -i -H "STRING" {} \;
  • Find all php files that contain the string STRING:
  1. find ./ -type f -name "*.php" -exec grep -i -H "STRING" {} \;
  • You can also use the grep command with the -R option to search for files by content:
  1. grep "STRING" -R /path/for/find
  • Replacing text in files:
  1. find ./ -type f -name "*.conf" -exec sed -i 's/OLDTEXT/NEWTEXT/g' {} \;
  • Bulk changes to access rights, setting access rights to 644 for all files in the current directory and all subdirectories:
  1. find ./ -type f -exec chmod 644 {} \;
  • Setting access rights to 755 for all folders in the current directory and all subdirectories:
  1. find ./ -type d -exec chmod 755 {} \;
  • Search for all html files containing the code “0;URL=http” and set all rights for them to 000 (useful for finding malicious code):
  1. find /var/www/exampleuser/data/ -type f -name "*.html" -exec grep -i -H "0;URL=http" {} \; -exec chmod -R 000 {} \;
  • Search for all php files in the specified wp-content/uploads directory, up to 3 attachments of all users of all server sites and set permissions for all of them to 000:
  1. find /var/www/exampleuser/data/www/*/wp-content/uploads/*/*/*.php -exec chmod -R 000 {} \;