«
»

Search for a string in multiple files

October 3rd, 2005 by George Notaras

There are times you need to search for a particular string or pattern in multiple text files. This is when grep proves to be a really handy tool. Type:

# grep -rsniH search_term *

The options mean:

r - be recursive
s - suppress any error messages
n - print the line number
i - do a case insensitve search
H - print the filename

Here are some examples:

# grep -rsniH hello *
# grep -rsniH '^the.*http:' *

The first searches all text files for the word “hello“. The second one searches for lines that begin with “the” and also contain “http:“.
You should check the grep man page for more info.

The Search for a string in multiple files by George Notaras, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Terms and conditions beyond the scope of this license may be available at www.g-loaded.eu.

Related Articles

Tags: ,

Bookmark and Share

2 Responses to “Search for a string in multiple files”

  1. Dotan Says :

    Nice tip – like it.
    however, when trying to detect strings in a C project, I do not want to search the object files:

    $> find . -name “*.c” | xargs grep expression

  2. Gnot Says :

    The same functionality can be achieved with:

    # grep -rsniH <expression> *.c

    But the use of "find|xargs" is an excellent addition!
    Thanks for your feedback.

Comments are automatically disabled after a certain period of time. Further discussion about the published content is still possible though in the G-Loaded Forums.