Learn how to find files using Terminal, Find and Grep

This tutorial will help you learn how to find files, or find files containing a given text using the terminal. We will use commonly “built-in” commands, such as : find and grep.

How to find files using Find:

First, open a terminal.

Most of the time, you will use the following command:

find / -name thefile.ext

This command will find every file or folder named thefile.ext in the whole filesystem (note that you must have some read rights on folders to list their content).
This command is recursive by default. This means it will look as deep as possible into the folder hierarchy. To avoid this, you can use the -maxdepth option:

find . -maxdepth 1 -name '*.html'

This will find every html files or folder in the current working directory without looking into subdirectories. This is non recursive. We have to use quotes to make sure that the shell does not expand the pattern, otherwise this would be like:

find . -maxdepth 1 -name index.html page.html contact.html main.html

You certainly noted that those commands may return folders as a result. You can avoid this by using the -type option:

find . -type f -name 'init*'

will find every file only that matches the given pattern, in the current working directory. This is a recursive search.
The -type option can use these values :

  • b      block (buffered) special
  • c      character (unbuffered) special
  • d      directory
  • p      named pipe (FIFO)
  • f      regular file
  • l      symbolic  link;  this  is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken.  If you want to search for symbolic links when -L is in effect, use -xtype.
  • s      socket

You can also find files using a lot of other parameters or patterns. For example, by date, by file/folder permission, by modification date, etc…

man find

to see the manuall pages about Find.

How to find files containing a given text using Grep:

It is really easy to use this command. By default, the search isn’t recursive, but you can use the -R option. Here’s a few examples:

grep -R 'password' *

This will show every file containing the text ‘password’ (without the quotes), it goes through the current directory and its subdirectories. It is recursive.

If you need to know the line number where the text has been found, use this, for example:

grep -n 'important' *.html

You will see every html files containing the word ‘important’ and for each result, you’see the file name and the line number.

Also you can use regular expressions, like this:

grep -R -e '[0-9] char' *

This finds every file which matches the given regular expression, recursively, starting from the current directory.

For more information on grep, you can read my other article “Differences between grep, egrep, fgrep” or type this command in a terminal:

man grep

3 Replies to “Learn how to find files using Terminal, Find and Grep”

Leave a Reply