Search For Files In Bash

by on February 15, 2007 · 2 comments· LAST UPDATED February 15, 2010

in

How do I search for file in Bash?

You can use the following commands to search for files in a bash shell:

  1. locate command - find files by name. It reads one or more databases created by updatedb and writes file names matching at least one of the PATTERNs to the screen, one per line. This may not contains file created within last 12-24 hrs.
  2. find command - search for files in a directory hierarchy in real time.

locate command in bash

To search a file called xorg.conf, enter:
locate xorg.conf
Sample outputs:

/etc/X11/xorg.conf
/etc/X11/xorg.conf.backup
/etc/X11/xorg.conf.failsafe
/home/vivek/Downloads/xorg.conf.txt
/usr/share/man/man5/xorg.conf.5.gz

Instead of writing file names on scree, write the number of matching entries only, enter:
locate -c xorg.conf
Sample outputs:

5

Ignore case matching (i.e. match foo.txt, FOO.TXT, foo.Txt and so on):
locate -i filename
Only find and limit search to one file at a time:
locate -n 1 filename
Only find and limit search to three files at a time:
locate -n 3 filename
To search for a file named exactly NAME (not *NAME*), use
locate -b '\FILENAME'
Find information about current databased created by the updatedb command:
locate -S
Sample outputs:

Database /var/lib/mlocate/mlocate.db:
	35,411 directories
	2,79,320 files
	1,96,50,749 bytes in file names
	77,85,226 bytes used to store database

find command in bash

The basic syntax is as follows:
find /path/to/dir -name "filename"
In this example, find httpd.conf file in /etc directory:
find /etc -name "httpd.conf"
To find all headers file *.h in /nas/projects directory, enter:
find /nas/projects -name "*.h"
Please see our previous FAQs about find command which covers many find command examples:

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 2 comments… read them below or add one }

1 ~ August 16, 2012 at 10:16 am

neither of these are helpful for me At All.

1. locate isn’t going to work. my whole system is less than 12 hours old.

2. what’s the point of using “find”, if i have to specify exactly where the file is in the first place?

Reply

2 nixCraft August 16, 2012 at 10:42 pm

If you don’t know the path, just specify / (to search entire system):

find / -type f -iname "filename-here"
find / -type f -iname "foo*.doc"

Reply

Leave a Comment

Tagged as: , , , , , , , , , , , , , ,

Previous Faq:

Next Faq: