Table of Contents

This is part 11 of the series Linux Command Line Interface. Please check earlier articles to get the grasp of current one.


Searching for a file or directory is difficult when there are hundreds or thousands of files, especially if we want to search based on its property. Linux got the following tools for these requirements.

  • grep
  • locate
  • find
File Searching in Linux
File Searching in Linux

Searching with grep command

grep searches for a word in a given file.

me@linux ~ $ ls /usr/share > test.txt
me@linux ~ $ grep mode test.txt

Instead of redirecting the output from ls /usr/share to test.txt file, the same output can be sent as input to the grep command. This process is called pipelining.

me@linux ~ $ ls /usr/share | grep mode

Searching with locate command

locate command searches for a word in a database, which consists of all file locations.

me@linux ~ $ locate zip

The above command will give a large result. If it won’t stop, press Ctrl + C. This result usually consists of all file locations which has string zip. This may be a file name or a directory name.

me@linux ~ $ locate bin/zip

Above result displays all file locations, which consists of string bin/zip.

Here is another example.

me@linux ~ $ locate sr/bin/z

Newly downloaded or created files/folders may not be displayed in the result when we search using locate program. Let’s download a file and check this operation.

me@linux ~ $ wget -O einstein.jpg

This will download an image einstein.jpg in home folder.

me@linux ~ $ locate einstein.jpg

Above command displays nothing if it can’t find the file in database. Database has to be updated to display the file in result.

me@linux ~ $ sudo updatedb
me@linux ~ $ locate einstein.jpg

Searching for files using find command

To display all your files in your home folder :

me@linux ~ $ find ~

Above result includes hidden files too. That’s the reason the list is so long.

To count total number of files in your folder -

me@linux ~ $ find ~ | wc -l

wc -l command counts total number of lines in the result. Each line represents a file location.

To count total number of directories:

me@linux ~ $ find ~ -type d | wc -l

To count total number of regular files:

me@linux ~ $ find ~ -type f | wc -l

Using find command with -name option

To find all jpg image files:

me@linux ~ $ find ~ -type f -name "*.jpg"

Try command me@linux ~ $ find ~ -type f -name "*.png". This will give all default png images in your home directory (possibly in hidden folders).

Here is an example if we remember only part of file name:

me@linux ~ $ find ~ -type f -name "*stein*"

Operators can also be used when we want to do one or more operations using find. General operators are and, or and not.

me@linux ~ $ find ~ \( -type f -name "*stein*" \) -or \( -type f -name "*.txt" \)