Find Command - Linux File Search Utility | Online Free DevTools by Hexmos

Master the Linux find command for efficient file and directory searching. Learn syntax, examples, and how to execute commands on found files.

Find Command

Linux Find Command: Efficient File Searching

The find command is a powerful and essential utility in Linux and Unix-like operating systems used to search for and locate files and directories within a specified directory hierarchy. It returns a list of files and directories that satisfy the criteria defined in the command's expression. Understanding the find command is crucial for effective command-line file management.

The basic syntax for the find command is:

find [starting point] [expression]

The [starting point] specifies the directory where the search begins, and [expression] defines the conditions for the search, such as name, type, size, or modification time. The -exec [command] option is particularly useful, allowing you to run a specified command on each file or directory found by find. By default, the results are newline-terminated. For scenarios requiring precise handling of filenames with spaces or special characters, the -print0 option can be used to make the results null-terminated, which is safer when piping output to other commands like xargs.

13.1. Common Find Command Examples

Searching Files by Name

To find files with a specific name, use the -name option:

find . -name demo.txt

This command searches the current directory (.) and its subdirectories for a file named demo.txt.

Finding Files with a Specific Pattern

You can use wildcards with the -name option to find files matching a pattern:

find ./Codes -name "*.cpp"

This searches within the ./Codes directory for all files ending with the .cpp extension.

Locating Directories by Name

To find directories specifically, use the -type d option along with -name:

find . -name Codes -type d

This will find all directories named Codes starting from the current directory.

Changing Permissions of Found Files

The -perm option allows you to find files based on their permissions. Here's how to find files with 777 permissions and change them to 644:

find . -type f -perm 0777 -print -exec chmod 644 {} \;

This command finds all files (-type f) with permissions 0777, prints their names, and then executes chmod 644 on each found file ({} represents the found file, and \; terminates the command).

Finding and Removing Files

You can use find to locate and remove files matching certain criteria. For example, to find and remove all files with the .bkp extension:

find . -type f -name "*.bkp" -exec rm -f {};

This command finds all files ending in .bkp and forcefully removes them (rm -f).

External Resources