Linux Commands Find find
• The find command in UNIX is a command line utility for walking a file hierarchy. • It can be used to find files and directories and perform subsequent operations on them. • It supports searching by file, folder, name, creation date, modification date, owner and permissions. • By using the - exec other UNIX commands can be executed on files or folders found. • Reference: https://shapeshed.com/unix-find/ Find by name
• To find a single file by name • pass the -name option • along with the name of the file you are looking for. Find by name
• Suppose the following directory structure exists
• The file foo.txt can be located with the find by using the -name option. Find multiple files
• Can use wild card characters find ./ -type f -name "*.sh" Find and delete
• To find and delete a file pass the --delete option to find. • This will delete the file with no undo so be careful.
find ./foo -name foo.txt –delete
• To be prompted to confirm deletion combine -exec with rm -i.
find ./foo -name foo.txt -exec rm -i {} \; Find a directory
• To find a directory specify the option -type d with find.
find ./foo -type d -name bar ./foo/bar Find by modification time
• To find files by modification time use the -mtime option followed by the number of days to look for. • The number can be a positive or negative value. • A negative value equates to less then so -1 will find files modified within the last day. • Similarly +1 will find files modified more than one day ago. find ./foo -mtime -1 find ./foo -mtime +1 Find by permission
• To find files by permission use the -perm option and pass the value you want to search for. • The following example will find files that everyone can read, write and execute find ./foo -perm 777 Find and operate on files • To find and operate on file us the -exec option. • This allows a command to be executed on files that are found. find ./foo -type f -name bar -exec chmod 777 {} \;
• All arguments after -exec are taken to be arguments to the command until an argument consisting of ';' is encountered.
• The string '{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command • not just in arguments where it is alone
• Both of these constructions might need to be escaped (with a '\') or quoted to protect them from expansion by the shell