Skip to content

Find command on Linux (find files)

The find command searches directly on the file system for files and directories. Depending on the size of the file system, this command can be very time-consuming.

Its basic syntax is:

$ find [path] [expression]

You must indicate a starting point for the search in the Linux directory tree. If you want it to start at the root, enter ”/”. If you want the search to start from the current directory, use “as the path. /“or simply dot”. ”.

Find allows a multitude of expressions such as search options, such as name, size, file creation date, access date, by file type, permissions, etc.

Examples:

Search for the file texto.txt starting from root (/), of the file type (f):

$ find/-name texto.txt -type f

Search for all files with the extension .txt from the current directory (.) :

$ find. -name “*.txt”

Search for the “users” directory from the current directory, regardless of whether it is written with capital or lower case letters:

$ find. -iname users -type d

Search for files that don’t end with .html from the current directory:

$ find. -type f -not -name “*.html”

Find also allows you to execute a command with the list of files it finds. In this example, find copies all of the .mp3 files found from the current directory to /tmp:

$ find. -type f -name “*.mp3” -exec cp {} /tmp/;

Delete all BACKUP directories found from the current directory:

$ find. -type d -name BACKUP -exec rm -r {};

Search for files modified in the last 7 days:

$ find. -mtime -7 -type f

Search for files edited before 5 days

$ find -mtime +5

Delete backup files older than 15 days:

$ find /backup/ -type f -mtime +15 -exec rm -f {};

Delete all object files found from the current directory:

$ find. -name “*.o” -type f -exec rm -f {};

Copy all files changed in the last 2 days to the /tmp directory:

$ find. -type f -mtime -2 -exec cp {} /tmp;

You can also search for a file that is more recent than a particular file:

$ find -newer source-file.c

Search for files with permission 0777:

$ find. -type f -perm 0777 —print

Search for all files larger than 50Mb:

$ find/-size +50M

You can combine the options, such as to search for files with a .php extension changed in the last 48 hours:

$ find -name '*.php' -mtime -2

Find can also be used to create a list of files in a directory, which can be ordered with the sort command:

$ find | sort<br></br>. <br></br>. /CapituloForm.php<br></br>. /CapituloList.php<br></br>. /Form.php<br></br>. /List.php<br></br>. /SubcapituloForm.php<br></br>.

/SubcapituloList.php

Conclusion

The find command is a powerful tool for finding files, directories, based on name, permissions, attributes, size, ownership (per user or per group), etc. It can be used to scan the system to find programs with suid permissions, correct permissions, make backups, etc.