Home » Linux

Search for a string in a directory of files

4 November 2013 No Comment
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)

folders

Suppose you have a string that you want to search in a directory. How would you do it? What if this directory contains many files and sub-directories? What if you want to search the string in a particular set of files?

One way to do it is by using grep. Grep is a powerful Linux command. When you provide a pattern to search, it can search the files you specified very quickly. It supports regular expressions too. For example, if you want to search for the word reboot in the current directory and sub-directories, you would run:

grep -r reboot *

This command will search every single file for that string. The downside to using grep is that it will search all files including binary files.

If you know what type of files you want to search, it will be faster to specify the file extension. For example, if you know the string is contained in a .txt file, you can search in those files only. Unfortunately, grep does not search recursively when you specify the file extension.

To search the word reboot in the current directory and sub-directories, you would run:

find . -name *.txt -exec grep reboot {} \; -print

This command will find all files with extension .txt, search for the word reboot in that file, and print out the line and filename that contains it.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

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

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.