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:
- find /var/www/ -name "file.conf"
- find /var/www/ -name "*.conf"
- Case insensitive search:
- find /var/www/ -iname file.conf
- Search by file size:
- find /home/user -size +10M
- Search by rights mask:
- find ./ -perm 700
- Search by date for files created or modified within the last 5 days:
- find /home/user -type f -mtime -5
- Files created or modified within the last 5 minutes:
- find /home/user -type f -mmin -5
- Find files created or modified older than 30 days (aka search for outdated files):
- find /path -type f -mtime +30
- Delete files created or modified older than 30 days:
- find /path -type f -mtime +30 -delete
- Time of last call for which is more than 5 days:
- find /usr/bin -type f -atime +5
- Search for a string in files:
- find ./ -type f -exec grep -i -H "STRING" {} \;
- Find all php files that contain the string STRING:
- 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:
- grep "STRING" -R /path/for/find
- Replacing text in files:
- 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:
- find ./ -type f -exec chmod 644 {} \;
- Setting access rights to 755 for all folders in the current directory and all subdirectories:
- 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):
- 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:
- find /var/www/exampleuser/data/www/*/wp-content/uploads/*/*/*.php -exec chmod -R 000 {} \;