Is it possible to make find more efficient to use than Find + Grep in this scenario

findgrep

I often find myself searching for a file in the current folder and subfolders based on part of its name. It seems to me that in this case find + grep requires less typing than only find. E.g.

find . | grep user   #19 chars typed

has to be written with only find:

find . -path "user*" #21 chars typed

It feels kind of silly to type more characters when using a single command that was meant to find files… then using two of them in combination.

Is there any way of making the use of only find to be more efficient in terms of characters typed?

Best Answer

Yes,

ff () {
    find . -path "*$1*"
}

This function is invoked as

ff user

and will return all pathnames (of files, directories etc.) in or beneath the current directory that contain the given string.

The function definition should go into your ~/.bashrc file (or the corresponding shell initialization file that is used by your shell) and will be usable in the next interactive shell that you start.


The following variation only considers the filename portion of the pathname:

ff () {
    find . -name "*$1*"
}

If you also want to restrict the results to only regular files, then add -type f to the find invocation:

ff () {
    find . -type f -name "*$1*"
}

Note that your command

find . -path "user*"

will never output anything. This is because every considered pathname will start with ..

And finally a word of caution: I'm assuming this will be used interactively and that you will use your eyes to look at the result. If you're planning to use it in a script or for doing any looping over filenames returned by the function, please see "Why is looping over find's output bad practice?".

Related Question