Finding files using macOS Terminal

Find files and text from the macOS Terminal: find, grep and mdfind, then fd, ripgrep and fzf, with measured speeds and 7 more tools worth knowing.

19 Feb 2025

Ways to Find Files in macOS Terminal

To find files in macOS Terminal, you can use several main commands:

  1. find - This command is used to search for files and directories in a directory hierarchy based on a specified expression.
  2. Example: find /path/to/directory -name "filename"

Use find to search for files or directories by name, type, size, etc.

  1. locate - Utilizes a pre-built database to quickly find files. The database needs to be updated periodically using sudo /usr/libexec/locate.updatedb.
  2. Example: locate filename

  3. mdfind - This command uses macOS's Spotlight indexing to search for files = fastest.

  4. Example: mdfind "search term"

  5. grep - While primarily used to search within files, it can be combined with other commands to search for files containing specific text.

  6. Example: grep -r "search text" /path/to/directory

grep stands for Global Regular Expression Print.
It is a command-line tool used in Unix-based systems (including macOS) to search for specific text patterns within files.

It searches for lines matching a pattern in files.

Use grep to search inside files for text.

  1. ls - Basic command to list files in directories, can be combined with other commands or options to refine search.
  2. Example: ls -R | grep "filename"

Each of these commands can be modified with various options to refine searches, such as filtering by file type or modifying search depth.

Goal Best Tool Why
By file content grep Searches inside files for matching text
By file name (fast) mdfind Uses macOS Spotlight index = very fast
By file name (portable) find Works on all Unix systems, doesn't rely on index
By file name (if indexed) locate Super fast, but needs sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist to enable DB
Just listing files ls Only shows what's in the directory, no search at all

Commands

find

  1. Basic Syntax:
  2. find [path] [expression] - Searches for files and directories starting from the specified [path] and matches them against the given [expression].

  3. Common Flags:

  4. -name [name]: Searches for files by name.
    • Example: find / -name "example.txt"
  5. -type [type]: Searches for a type of file. [type] can be f for files or d for directories.
    • Example: find /path/to/directory -type f
  6. -mtime [n]: Finds files modified n days ago.
    • Example: find . -mtime -7 (modified in the last 7 days)
  7. -size [n]: Finds files of a specific size. [n] can be in kilobytes (k), megabytes (M), etc.
    • Example: find / -size +10M
  8. -exec [command] {} \;: Executes a command on each matching file.

    • Example: find . -name "*.txt" -exec grep "searchtext" {} \;
  9. Logical Operators:

  10. -and: Combines expressions (can be omitted, as it's the default).
  11. -or: If either expression is true, the file is a match.
  12. !: Negates an expression.

  13. Examples:

  14. Search for files owned by a specific user: find / -user [username]
  15. Find empty files: find /path/to/directory -type f -empty
  16. List files created within the last 24 hours: find / -ctime -1

locate

The locate command in macOS is used to quickly find files by searching through a pre-built database. Here are the basic aspects and options associated with the command:

  1. Basic Usage:
  2. locate [filename]: Searches for files matching the given [filename] within the system database.

  3. Update the Database:

  4. sudo /usr/libexec/locate.updatedb: Updates the database used by the locate command. This command may require superuser privileges.

  5. Options:

  6. -i: Ignore case distinctions in patterns and data.
    • Example: locate -i "example.txt"
  7. -d [path-to-database]: Specifies an alternative database for locate to use.
    • Example: locate -d /my/other/database "search_term"
  8. -r [expression]: Interprets the search term as a regular expression.
    • Example: locate -r 'my.*file'

The locate command is generally faster than find because it relies on an indexed database of system paths, which must be updated manually or may be scheduled to update periodically. This speed comes at the cost of potentially having less up-to-date results compared to real-time search methods.

mdfind

The mdfind command in macOS uses the Spotlight index to search for files. Here are the essential options and usage examples:

  1. Basic Usage:
  2. mdfind "search text": Searches for files that match the specified query using Spotlight's index.

  3. Search by File Type:

  4. mdfind "kMDItemContentType == 'public.text'": This example searches for all text files. You can replace 'public.text' with the relevant content type for other file types.

  5. Search in Specified Directory:

  6. mdfind -onlyin /path/to/directory "search text": Limits the search to a specific directory.

  7. Refining the Search:

  8. mdfind "kind:image" && mdfind "date:today": You can use Spotlight attributes like kind, date, etc., for more refined searches.

  9. Search by Metadata:

  10. mdfind -name "example.txt": Searches specifically by file name.

  11. Exclude System Files:

  12. mdfind -0 "search text": Searches without descending into system files, useful for excluding hidden or system-specific files.

The mdfind command is very powerful when you need to perform quick searches across the entire system based on indexed metadata. It benefits users looking for a more efficient search than some of the more extensive real-time searches like find.

grep

The grep command is used for searching text within files in macOS Terminal. Here are the basic options and usage examples:

  1. Basic Usage:
  2. grep "pattern" [file]: Searches for the specified "pattern" within the provided [file].
  3. Example: grep "error" logfile.txt

  4. Recursive Search:

  5. grep -r "pattern" [directory]: Searches recursively through all files in the specified directory.
  6. Example: grep -r "TODO" ./project

  7. Ignore Case Sensitivity:

  8. grep -i "pattern" [file]: Ignores case distinctions when searching.
  9. Example: grep -i "warning" logfile.txt

  10. Display Line Numbers:

  11. grep -n "pattern" [file]: Displays the line number along with each match.
  12. Example: grep -n "error" logfile.txt

  13. Count Matches:

  14. grep -c "pattern" [file]: Counts the number of lines that match the pattern.
  15. Example: grep -c "error" logfile.txt

  16. Show only Matching Part:

  17. grep -o "pattern" [file]: Prints only the matching part from each line.
  18. Example: grep -o "http://[a-zA-Z0-9./]*" logfile.txt

These options make grep a versatile tool for processing and extracting information from text files in a variety of contexts.

ls

The ls command in macOS Terminal is used to list directory contents. Here are the basic options and commands:

  1. Basic Listing:
  2. ls: Lists files and directories in the current working directory.

  3. List with Details:

  4. ls -l: Provides a detailed listing, showing file permissions, number of links, owner, group, size, and modification date.

  5. Include Hidden Files:

  6. ls -a: Shows all files, including hidden ones (those starting with a dot .).

  7. List with Human-Readable Sizes:

  8. ls -lh: Displays sizes in a more readable format such as KB, MB, rather than bytes.

  9. Sort by Modification Time:

  10. ls -lt: Sorts files by modification time, most recently modified first.

  11. Recursive Listing:

  12. ls -R: Lists all files and directories with their subdirectories recursively.

  13. Combining Options:

  14. You can combine multiple options. For example, ls -la will show detailed information including hidden files.

These options allow you to customize the display of directory and file listings according to your needs.


Faster tools

20 Sep 2026 the commands above work on any Unix box and are worth keeping for that reason. Everything below is faster, and most of it is already installed here.

Already on this Mac: fd, rg, fzf, zoxide, yazi, plus the built-in mdfind. That set (fd, ripgrep, fzf, zoxide, yazi) is also what the terminal crowd on X has converged on.

Tool Replaces What it does
fd find Filename search, skips hidden and ignored files by default
rg grep -r Content search, parallel, .gitignore aware
fzf nothing Fuzzy filter for any list, pipes into anything
zoxide cd Jumps to directories by how often you use them
yazi browsing by ls File manager with previews, calls fd and rg inside
mdfind find on macOS Spotlight index, whole disk, instant

Measured here

30 Nov 2026 re-run: the same kinds of search, each run once to warm the cache, then timed 3 times. The chart shows the median.

Bar chart of search times. Content search for kaltura in 99,893 files: grep 33.64s, rg -uu 10.77s, rg 8.72s, mdfind 0.19s. Filename search for invoice in 879,644 files and folders: find 26.91s, fd -HI 9.46s, mdfind 0.87s, fd 0.39s

Search Corpus Command Time Found
Content 99,893 files in ~/sites grep -ril 33.64s 89
Content Same rg -li -uu 10.77s 89
Content Same rg -li 8.72s 89
Content Same mdfind -onlyin ~/sites 0.19s 80
Content Whole home directory mdfind -onlyin ~ 5.14s 201,655
Filename 879,644 files and folders in ~/ai find -iname 26.91s 124
Filename Same fd -HI 9.46s 124
Filename Same mdfind -onlyin ~/ai -name 0.87s 15
Filename Same fd 0.39s 4
Filename Whole home directory mdfind -onlyin ~ -name 1.04s 1,799

What the numbers say:

  • The index wins, but it isn't complete. Spotlight answered the content search 177 times faster than grep. It also missed 12 files that rg found: 8 pages the site generator rewrote the day before, 3 HTML pages from April 2025 and 1 JSON file written that morning. And 3 of its 80 hits were folders with "kaltura" in the name, because mdfind matches names as well as text. A gap in the index looks exactly like "no match".
  • ripgrep's lead is the engine, not the skipping. rg -uu reads hidden and ignored files too, the same set grep reads, and it is still 3 times faster.
  • fd's lead is mostly the skipping. Plain fd took 0.39s and found 4 files. With -HI it found all 124 in 9.46s, still 3 times faster than find. Most of ~/ai is hidden or .gitignored: virtual environments, node_modules, caches.
  • A broad mdfind pays for its output. The whole home directory took 5.14s for "kaltura", because it printed 201,655 paths. Scope it with -onlyin.

20 Sep 2026 first run, for reference: grep -ril 32.08s and rg -li 6.64s on ~/sites, fd 0.42s and fd -HI 1.34s on what was then 149,863 files in ~/ai.

Recipes

# filename, current directory down
fd invoice

# include hidden files and ignored paths
fd -HI invoice

# by extension, then run something on each hit
fd -e md -x wc -l

# content, case-insensitive
rg -i kaltura

# just the file names, not the matching lines
rg -l kaltura

# restrict to a language
rg -t py argparse

# pick a file interactively, then open it
fd -t f | fzf | xargs open

# Spotlight: content, anywhere, instant
mdfind -onlyin ~ "gap selling"

# Spotlight: files over 1GB
mdfind 'kMDItemFSSize > 1073741824' -onlyin ~

# Spotlight: filename only
mdfind -onlyin ~ -name 260909-digitalx

⚠️ WARNING: mdfind only knows what Spotlight indexed. External drives, network shares and privacy-excluded folders return nothing, which looks exactly like "no match". Check the volume first with mdutil -s /Volumes/NAME, and fall back to fd or rg when it is not indexed.

Worth knowing, not installed

Tool Why look
tgrep Trigram-indexed grep from Microsoft, aimed at repos too big for rg
television Fuzzy finder with ready-made channels: files, text, git, env
broot Tree navigator that folds a huge directory onto one screen
ugrep grep-compatible flags, searches inside archives and PDFs
skim fzf, rewritten in Rust
fselect SQL over the filesystem: select name from . where size gt 10mb
ast-grep Searches code by syntax tree instead of text

The indexed tools are the interesting direction. On a Mac the index already exists and is free, so mdfind covers most of that ground.

30 Nov 2026 each one in more detail. Star counts and install commands as of today.

tgrep

What it is: grep with an index, from Microsoft (MIT licence, 3,500 stars). It splits every file into trigrams, 3-character chunks, and stores which files hold which trigram. A search first asks the index which files could match, then runs the regex only on those. It already powers search in GitHub Copilot CLI.

The claim: in Microsoft's August 2026 benchmark it beat ripgrep in 17 of 18 repo and platform combinations, from 0.93x to 51.9x. That is search time with the index built and a server running. Building the index isn't counted.

# no Homebrew formula: build from source with Rust
git clone https://github.com/microsoft/tgrep.git && cd tgrep
cargo install --path tgrep-cli --locked

tgrep serve .                        # build the index, keep it fresh in the background
tgrep -- "fn main" .                 # search; uses the server when it runs
tgrep status .                       # indexing and refresh status
tgrep index . --exclude vendor       # one-off index without a server, in .tgrep/
tgrep --no-index -- "TODO" .         # skip the index when results must be current

The catch: the same one as mdfind. The index can lag the files, and a pattern with no useful trigrams still scans everything. Worth it on a monorepo searched 100s of times a day. Not for my scripts folders, where rg already answers in seconds.

television

What it is: a fuzzy finder, like fzf, that ships its own data sources. The command is tv (MIT, 6,500 stars). fzf filters whatever you pipe into it. tv has channels: files, file contents, git repos, environment variables, Docker containers, each with its own preview.

Television in a terminal: the env channel filtered on car, with the channel picker open over it listing git-log, git-diff, git-repos and other git channels, and a description of the git-repos channel

brew install television

tv                  # files in the current directory
tv text             # file contents, with a preview of the matching line
tv git-repos        # every git repo on the disk, previewing its log
tv env              # environment variables

# Ctrl+T for files and Ctrl+R for history, in place of fzf's bindings
eval "$(tv init zsh)"

A channel is a small TOML file, so a new source takes 10 lines:

# ~/.config/television/cable/notes.toml
[metadata]
name = "notes"
description = "My notes"

[source]
command = "fd -e md . ~/notes/site/content/articles"

[preview]
command = "bat --color=always '{}'"

Versus fzf: the same job, less glue. If your .zshrc already holds 5 fzf functions with --preview, you have built television by hand.

broot

What it is: a tree view that fits any directory on 1 screen (MIT, 13,000 stars). Where tree prints pages, broot shows the first few entries of each folder and folds the rest into "51 unlisted". Type a few letters and the tree narrows to the matches while keeping their parents in view.

broot overview of a source directory: folders with sizes, the first 2 or 3 files of each, and lines such as 51 unlisted and 25 unlisted for the rest

brew install broot
broot --install     # adds the br shell function, so broot can cd for you

br -s               # tree with sizes
br -sdp             # sizes, dates and permissions

Inside broot:

Type Does
invo Fuzzy match on names
/inv.*26 Regex on names
c/kaltura Search inside files
Alt+Enter Quit and cd to the selected folder
Alt+H Toggle hidden files
Alt+I Toggle .gitignored files

broot content search with c/memm: the tree shows only the files containing memmap, with the matching text in green next to each file name

Versus yazi: yazi is the file manager I use, with image previews, see Terminal File Managers. broot is better at 1 job: seeing the shape of a big unknown folder and jumping into it.

ugrep

What it is: a drop-in replacement for grep (BSD licence, 3,300 stars). Same flags, so scripts keep working, plus what grep never had: an interactive search screen, fuzzy matching, and search inside archives, PDFs and Office files. Its authors say it is usually faster than ripgrep, on their own benchmarks.

Animated terminal recording of ugrep's query screen: typing todo filters matches across C files live, with file names, line numbers and highlighted hits

brew install ugrep

ug -Q                          # interactive: results update as you type
ug -z "invoice" ~/Downloads    # inside zip, tar and gz files too
ug+ "Kündigung" ~/Documents    # inside PDFs and Office files, through filters
ug -Z2 "kaltrua"               # fuzzy: up to 2 typos still match "kaltura"
ug -l "kaltura" ~/sites        # same -l as grep

ug+ hands each PDF to pdftotext (from brew install poppler) before it searches. That is the gap rg leaves open: text locked inside documents. On this Mac, Spotlight already indexes PDF text, so mdfind covers the common case. ugrep is for folders Spotlight doesn't see, such as a NAS share.

skim

What it is: fzf rewritten in Rust, with the command sk (MIT, 7,000 stars). Most fzf flags carry over, and the shell bindings are the same, Ctrl+T and Ctrl+R.

skim listing ripgrep matches for preview in a Rust project on the left, with a preview pane on the right showing the selected CHANGELOG line in context

brew install sk

fd -t f | sk --preview 'bat --color=always {}'

# interactive mode: every keystroke re-runs rg with the query
sk --ansi -i -c 'rg --color=always --line-number {q}'

The difference: interactive mode, where the query is fed to a command instead of filtering a fixed list. fzf does the same today with --disabled and a reload binding. No reason to switch if fzf is already set up, which it is here.

fselect

What it is: file search written as SQL (Apache 2.0, 4,500 stars). Not real SQL, a relaxed version: columns, from, where, order by, limit, even group by. It also reads what find can't: image size, EXIF, audio tags, MIME type.

brew install fselect

# the 10 biggest files under Downloads
fselect size, path from ~/Downloads order by size desc limit 10

# photos at least 4,000 pixels wide
fselect width, height, path from ~/Pictures where width gte 4000

# PDFs changed this week, as JSON
fselect path, modified from ~/Documents where ext = pdf and modified gt '2026-11-23' into json

# how much space each file type uses
fselect "ext, count(*), sum(size) from ~/Downloads group by ext"

Readable 6 months later, unlike find ~ -type f -size +100M -mtime -7 -exec ls -lh {} \;. Slow on a big tree, because it walks the disk like find.

ast-grep

What it is: search and replace on code structure, not text (MIT, 16,800 stars). The command is ast-grep, or sg. You write the pattern as code, with $A standing for any expression. It parses the files, so it ignores formatting, comments and strings that only look like code.

ast-grep in a terminal rewriting TypeScript: the pattern $A && $A() becomes $A?.(), shown as a diff where os.homedir && os.homedir() turns into os.homedir?.()

brew install ast-grep

# every call to print() with exactly 1 argument
ast-grep -p 'print($A)' -l py

# every requests.get without a timeout
ast-grep -p 'requests.get($URL)' -l py ~/ai

# rewrite: open() without encoding gets encoding="utf-8"
ast-grep -p 'open($F, "r")' -r 'open($F, "r", encoding="utf-8")' -l py -i

rg "requests.get" finds the calls with a timeout too. ast-grep finds only the ones without, because requests.get($URL) matches 1 argument and no more. It's a refactoring tool more than a search tool, and the one I'd install first from this list.

Which one

  • Inside a project: rg for text, fd for names. They respect .gitignore, so results stay clean.
  • Anywhere on the Mac: mdfind. Nothing beats a warm index.
  • Don't know the name: fd -t f | fzf, or open yazi and browse with previews.
  • On a server over SSH: find and grep. They are always there, which is the whole point of keeping the first half of this note.