Pete Freitag Pete Freitag

Searching for files by file name on Mac or Linux

Published on January 07, 2020
By Pete Freitag
linux

Have you ever had to find a file by a file name or file extension? Sure you have! Here's how I locate a file when I'm using a Mac or Linux shell.

The find command

The find command is really handy because it will list every file in the current directory and all sub directories. You can also give it a path, so if you want to search just your home directory (and it is not your current working directory) you can just run:

find ~

And that will list every single file in your home directory (The ~ is a shortcut for home directory).

The find command will be installed by default on your Mac, and just about every linux distribution.

While that is handy, it might list out thousands of files, so our next step is to search the results for the file name we are looking for.

The grep command

The grep command can be used to search the output of another command by using the | pipe operator. For example if I run:

find ~ | grep log

I can search my home directory for any file with log in the file name (or directory name).

Since grep supports regular expressions, if I just want to search file files ending in .log I can do that like this:

find | grep '\.log$'

Searching by file name using find

After my initial thought to use grep, I realized that the find command also has a lot of builtin options you can leverage, so we can simplify this by using:

find -name '*.log'

There are a bunch of options you might find handy, run man find to see them all.

Some of you might say that you can just use Finder on a Mac to search for files by name, and you'd be correct, that also works, but this is much faster and more flexible.



mac linux find grep tips

Searching for files by file name on Mac or Linux was first published on January 07, 2020.

If you like reading about mac, linux, find, grep, or tips then you might also like:

Weekly Security Advisories Email

Advisory Week is a new weekly email containing security advisories published by major software vendors (Adobe, Apple, Microsoft, etc).

Comments

I'm a fan of fd: https://github.com/sharkdp/fd
by Jim on 01/08/2020 at 2:03:31 PM UTC
On MAC the option -name isn't present and runs correctly on a linux machine.
plz correct the blog or clarify my doubt.
by Anon on 02/18/2020 at 5:40:28 AM UTC