How to use "find" command in Linux

How to use "find" command in Linux

·

3 min read

As name implies find command is used to find files/directories in the Linux System.

It recursively lists all the files/directories in the provided path.

  • man find to get manual of find command

  • /- any_option to look for more info of specific option

Syntax:

  • find [filters]

  • find [path] [filters] [criteria] [actions]

path: Starting directory for search

  • If no path is given, current path is consider by default.

  • . for current path

  • / for root path, searches in the whole system

filters: Additional conditions for search

  • Many Filters can be combined as we want. The default operation performed is AND.

  • Use -o so that Result is diplayed when either of the condition is met or true, useful when multiple filters applied

  • -name is most used filter, it is use to search for exact filename.

  • -mindepth, -maxdepth filters are used to control how deep the find recurses.

  • -not to invert filters, when used that expression will be excluded or not shown

  • -type [f or d] (type of file to search, f for files, d for directories)

  • -size [+ or -] (Matches files based on their size, + for greater, - for lesser)

  • -empty for finding empty files as a way to declutter

criteria: For filtering or locating files/directories

  • * is used to search for multiple files.

actions: Perform a specified command on each and every matched file/directory.

  • {} is a placeholder that represents the current file or directory.
  • -delete to delete all matched files/folders

  • -exec executed the specified command


Find all files in a current path

find . -type f

Find all directories in a current path

find . -type d

Find a file/folder with Exact name

find path_to_search/ -name filename.txt

find / -name foldername

Find all empty files

find . -type f -empty

Find all the files with .jpg extension

find -name '*.jpg'

Find all the files with either .jgp OR .png extension

find -name '*.jpg' -o -name '*.png'

Find all the files/folder which are min 2 Directories deep

find path/ -mindepth 2

Find only the files/folders that are directly inside the path we provided

find . -maxdepth 1

Find all the files which are not ending with .jpg

find . -type f -not -name '*.jpg'

Find all files with size greater than 10 MB

find path/ -type f -size +10M

Find files with only size less than 10 MB

find path/ -type f -size -10M

Delete all the files with size less than 10 MB

find path/ -type f -size -7M -delete

List sha384sum of all the files

  • {} represents current file/directory

  • ; to tell where command ends

  • \ to escape ";"

find path/ -type f -exec sha384sum {} \;

Thanks to My Guru Tom Hudson (aka tomnomnom) for this Beautiful guide