Quickly Search for Files in Unix Terminal

find is a powerful command-line utility but most of the time I just really need to search for matching files and directories in the current directory. I also usually end up grep-ing the output and using wildcards around the argument.

So why not just simplify the whole thing?

Creating a simple function that does that for us would be the way to go, so this should do the job:

1
2
3
search() {
    find . -iname "*$1*" -d | sed 's/^..//' | grep -i --color "$1"
}

Let me explain what this does. find does a case-insensitive -iname search in the current directory . of all the files and folders matching the provided string "*$1*" and also looks in sub-directories -d. Then sed deletes the first two characters of each line (they are ./) to clean up the results. grep -i is then used to highlight the string in the results.

You can use it like this:

1
2
3
4
$ search vim
Vim/.vimrc
Vim/vundles.vim
Vim

You can now add this function to your .bash_profile or better yet, your .dotfiles so it always gets loaded in to your shell session. I’ve modified this function a bit more to accept multiple arguments:

1
2
3
4
5
6
7
8
9
10
11
12
search() {
    if [[ $# -eq 0 ]] ; then
        echo "no arguments provided"
        echo "usage: search string [string2 string3 ...]"
        echo ""
    else
        for i in "$@"; do
            find . -iname "*$i*" -d | sed 's/^..//' | grep -i --color "$i"
            echo ""
        done
    fi
}

Now go! Be Free!