How to Search for Text in Files on Ubuntu

Looking for a way to search for text in files on Ubuntu? You should get a grip on the Ubuntu grep command.

Ubuntu grep command searches input FILE or FILES for lines containing a match to the given PATTERN. By default, grep prints the matching lines.

For your information grep stands for Global Regular Expression Print.

So do I need to know regular expression to use grep?

For simple searching you don’t need to be a regular expression guru. Remember the simplest regular expression (regex) is simply a word, or more generally, a string of characters.

Search for the given text in a single file

The basic usage of ubuntu grep command is to search for a specific string (text) in the specified file as shown below.

Syntax:
grep "literal_string" filename

$ grep "this" demo_file
this line is the 1st lower case line in this file.
Two lines above this line is empty.

grep has returned two lines containing our search term “this” in the demo file.

Checking for the given string in multiple files.

Syntax:
grep "string" FILE_PATTERN

$ grep "this" demo_*
demo_file:this line is the 1st lower case line in this file.
demo_file:Two lines above this line is empty.
demo_file:And this is the last line.
demo_file1:this line is the 1st lower case line in this file.
demo_file1:Two lines above this line is empty.
demo_file1:And this is the last line.

In this example we have used two files demo_file and demo_file1 in the current directory containing same content. See how grep has printed the name of the file first then the line containing search term.

Searching in all files recursively

You can use -r option if you want to search in all the files under the current directory and its sub directory. The following example will look for the string “geeks” in all the files in the current directory and all it’s subdirectory.

$ grep -r "geeks" *

Case insensitive search using grep -i

Syntax:
grep -i "string" FILE

This searches for the given string/pattern case insensitively. So it matches all the words such as “geeks”, “GEEKS” and “Geeks” case insensitively.

Till now we have searched for specific string/text in file or files. What happens when we don’t know the exact text to search?

Here comes Pattern or Regular Expression. We can search for a pattern if they are crafted in regular expression with grep.

Match regular expression in files

Syntax:
grep "REGEX" filename

A regular expression (REGEX or REGEXP) is a special text string for describing a search pattern. This one page guide of regular expression will quickly get you up to speed with regular expressions.

Need more geekary? Commandlinefu.com This is a linux command repository of the most elegant and useful linux commands. Great commands can be shared, discussed and voted.