The find Command
The find command is a powerful utility for locating files within a directory hierarchy. Available on Unix, Linux, and macOS systems, it supports various search criteria including filename patterns, file types, modification times, and permisions.
Basic Syntax
find [path] [expression]
The command traverses the specified directory tree and evaluates each entry against the given expression.
Searching in Home Directory
To locate files matching a pattern within the user's home directory:
find ~ -name "nginx.conf*"
The -name option performs case-sensitive pattern matching. Wildcards like * match any sequence of characters, so nginx.conf* matches files such as nginx.conf, nginx.conf.default, or nginx.conf.backup.
Searching in Specific Directories
To search within a particular directory rather than the entire filesystem:
find /etc -name "nginx.conf*"
This command restricts the search to the /etc directory and its subdirectories, making the operation faster when the approximate location is known.
The mdfind Command (macOS)
The mdfind command provides command-line access to Spotlight's metadata endexing. Since it relies on Spotlight's index, the search performance is significently faster than filesystem traversal, though the index must be enabled for the command to function.
Basic Usage
mdfind -name "nginx.conf"
The -name flag searches filenames only. Without this flag, mdfind searches across both filenames and file contents.
Searching File Contents
To find files containing specific text:
mdfind "mongodb"
This locates all indexed files whose content or filename contains "mongodb".
Searching Within Specific Directories
mdfind -onlyin /var nginx.conf
The -onlyin parameter restricts the search scope to the specified directory tree. This command searches for nginx.conf files within /var and its subdirectories only.