Sheharyar Naseer

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:

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:

$ search 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:

search() {
    if [[ $# -eq 0 ]] ; then
        echo "no arguments provided"
        echo "usage: search string [string2 string3 ...]"
        echo ""
        for i in "$@"; do
            find . -iname "*$i*" -d | sed 's/^..//' | grep -i --color "$i"
            echo ""

Now go! Be Free!