Command Line Basics: Finding Files

October 15, 2011 by
Filed under: command line, HowTo, linux 

In today's post I'm going to show how to use the command line find program to search for files. There are certainly different GUI tools available in Linux, such as Beagle, to search for files. The advantage of many of these systems is that they index the files on your system so that the searching is rather fast. The disadvantage is that the indexing can often slow down system performance, so many users end up disabling it. There's also the situation where you might not have access to a GUI, like when you're logged in to your web hosting server through ssh.

I'm going show the most basic use case for find: a search based on file name. In this form, the find command will be followed by a path telling where you want to search. You will then include the -name switch and specify a name pattern to match or a complete file name. If you use special characters in your pattern, like *, make sure to enclose them in single or double quotes. So the command is going to take the following form:

find {path} -name {name pattern to match}

For the first example I'll show how to search for files with a .txt extension in your current directory and below. This command uses the built-in shortcut "." to specify the current directory.

find . -name '*.txt'

Now you'll notice that the above command found all files with names that end in .txt in the current directory and all subdirectories. If you would like to limit the output to not include subdirectories, use the -maxdepth option.

Affiliate Link
find . -maxdepth 1 -name '*.txt'

Both of the above commands will find files that end in .txt, but not .TXT. If you'd like to find both, use the -iname switch instead of the -name switch.

There are many more options available with the find command. You can check it all out in the manual page.

man find

As you can see, it's a powerful tool, but its true power really comes through when you want to perform a function on several files at once. You can use find to generate a list of files and then pipeline the output to another command to operate on those files.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>