80x24

Code vs. The World

A Simple Bash Script To Find Files

If you spend a lot of time on the command line like I do, you’re probably familiar with using a combination of find and grep to search directories.

While they always get the job done, both find and grep don’t always have the most sensible defaults. I usually find myself searching for a case insensitive keyword that should be in the filename, file content, or both.

This is cumbersome to do with find and grep, and usually results in running two separate commands: one that searches only filenames and another that searches only file content. While grep can be used for this, it is often slow searching over many files. The solution to this is ripgrep, a tool that is faster than both ack and grep.

The script below combines both find and ripgrep to easily search for any file that contains your keyword. Usage: faf <directory> <filename>

Download it here or use the code below. If you don’t want to use ripgrep, you can always replace the instances of rg with the appropriate grep options. This script has been tested to work on Linux, but should work on macOS and BSDs as well.

#!/bin/bash
# This program uses find and ripgrep to find files that either match
# the filename or contents of the search.
if [ $1 == "--help" ]
then
    echo "Usage: <directory> <filename>"
else
    if [ "$#" -eq 1 ]
    then
        { find . -iname "*$1*" -type f -printf '%P\n' & rg -li $1; } | sort | uniq 
    elif [ "$#" -lt 3 ]
    then
        { find $1 -iname "*$2*" -type f -printf '%P\n' & rg -li $2 $1; } | sort | uniq 
    
    else
        echo "Usage: <directory> <filename>"
    fi
fi