When I first heard about fzf, I didn't understand why anyone would use it. I had a vague idea of what it did, but I didn't feel like I needed it at the time. That all changed when I moved halfway across the world for a software engineering role in 2023. I was struggling at my new job and started looking for a fix.
## What is fzf?
fzf is a command-line fuzzy finder. Opening a terminal and typing fzf will launch a fuzzy search over the names of all files in the current directory. As you type, the results will be filtered, and pressing Enter will print the name of the selected file.
$ fzf
▌ hello_world.txt ▌ hello.txt > hlo
hello.txt
If you aren't familiar with the CLI, there's a good chance you're struggling to imagine a practical application for this. On its own, fzf is mostly useless - the magic happens when you leverage its fuzzy searching to supercharge other CLI tools.
## fzf + nvim
To open a file in nvim (neovim), you need to pass the relative path to the file as the first argument.
$ nvim filename.txt
This quickly starts to feel cumbersome when you can't remember the exact name of the file, or it's buried in a deeply nested directory - if only there was a way to quickly search through all the files in the current directory...
$ nvim $(fzf)
This is called a "command substitution". It allows the nvim command to receive the output of the fzf command as its first argument. When you run this command, you'll launch a fuzzy search over all the files in the current directory, but when you press Enter, the selected file will immediately be opened in nvim. I use the following terminal alias daily - it's just a more robust version of the previous command.
alias s='file=$(find . -type f | colrm 1 2 | fzf) && nvim $file'
## fzf + cd
cd has the same constraint as nvim - it requires a relative path as its first argument. The main difference is that when I run cd, I'm usually moving to a completely different directory - not going more deeply into the current directory - so how does fzf help out here if it only fuzzy finds over files in the current directory? Simple - if you pass data to fzf over STDIN, it will fuzzy-find over your input text instead. I have the following alias to quickly switch between my projects or other commonly-accessed directories:
DIRS=$(cat << --- ~/.config/nvim ~/.config/tmux ~/projects/website ~/projects/command-reference ~/projects/sddm-theme ~/.dotfiles --- ) alias d='dir=$(echo $DIRS | fzf) && eval cd $dir'
This allows me to run the command d, type a couple of characters to narrow down to a single directory, and press Enter to immediately switch to that directory. I use this multiple times per day.