Wednesday, 6 May 2015

grep Commands In Linux / UNIX – Examples


First create the following "grep_text.txt" that will be used in the examples below to demonstrate "grep" command. I will show the content of the file "grep_text.txt".



The highlighted portion is the content in the file "grep_text.txt".


1)
Search for the given string in a single file

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

Syntax:
            grep "literal_string" filename




2)
Checking for the given string in multiple files.

Syntax:
       grep "string" FILE_PATTERN

For that i have to create another file named "grep_command.txt". and the content of the file "grep_command.txt" is given bellow:


The highlighted portion is the content in this file.

Next i am going to search the word "hello" in this two files.


When we search a string pattern in two or more files then the first word is the file name which the string pattern is found.


3)
Case insensitive search using grep -i

Syntax:
          grep -i "string" FILE_NAME




4)
Match regular expression in files

Syntax:
grep "REGEX" filename



This is a very powerful feature, if you can use use regular expression effectively. But it is case sensitive search.

From documentation of grep: A regular expression may be followed by one of several repetition operators:

    ?        The preceding item is optional and matched at most once.
    *        The preceding item will be matched zero or more times.
    +       The preceding item will be matched one or more times.
    {n}    The preceding item is matched exactly n times.
    {n,}   The preceding item is matched n or more times.
    {,m}   The preceding item is matched at most m times.
    {n,m} The preceding item is matched at least n times, but not more than m times.


5)
 Checking for full words, not for sub-strings using grep -w

If you want to search for a word, and to avoid it to match the substrings use -w option. Just doing out a normal search will show out all the lines.

The following example is the regular grep where it is searching for “is”. When you search for “is”, without any option it will show out “is”, “his”, “this” and everything which has the substring “is”.




6)
Search a string Recursively in all Directories

If you would like to search for a string in the current directory along with all of the subdirectories, you can specify the –r option to search recursively: