Walker News

How To Use Linux Find Command To Search Files?

The locate command is simple to use but it is not powerful as find command that allow user to perform “complex” file search and apply action for the searched file at one go.

Here are few examples of using Linux find command:

To find configuration files that contains a word or string (e.g.
find /etc -type f -size -200k -exec grep -HIils "127\.0\.0\.1" {} \;

  • “-type f” means search for regular file only (not symbolic link, pipe, directory, etc).
  • “-size -200k” means search for files below or less than 200KB only (file that is exactly 200KB or bigger is discarded).
  • “-exec” is to execute another Linux command for files returned by find command. The {} is place-holder (variable) used to keep or store the file returned by find command (one file at a time). The “\;” is sort of terminator.

To move all core dump files to a folder called coredir:
find /tmp -type f -name "core*" -exec mv {} coredir \;

Notice the position of {} (place-holder) used in mv command? Recall the mv command syntax, you should know why it is there, how to place the place-holder/variable of -exec option.

To search all files bigger than 1MB in Linux filesystem (so start from / directory):
find / -type f -size +1M -exec ls -lSh {} \;

The option for searching files by file size is useful when doing housekeeping to free up more disk space. Although it is possible to execute rm command using -exec option, I rather play safe by output the result to a file and examine it carefully:
find / -type f -size +100M -exec ls -l {} > /tmp/bigfiles.log \;

Then, you may use awk command to convert bigfiles.log to shell script that run rm command to delete them safely.

If you’re pretty confident and want to go ahead executing rm command using find (for example to delete all core dump files that no longer useful or hardly be used):
find /tmp -type f -name "core*" -exec rm -iv {} \;

The -iv option switches are insurance – the “-i” option get rm command to prompt for confirmation before deleting the file and “-v” option is to print the deleted file. Of course, you can omit the switches for sake of speed (if you’re confident)!

Type man find to get more information about find command options and usage.

Custom Search

2017  •  Privacy Policy