Unix

grep command in Unix/Linux

Grep stands for “Global Regular Expression Print”, grep is a search operation. It is one of the widely used command in unix. We are using grep mostly finding words. We can analyze the large sets of log files with help of grep command.
Syntax of grep command is

The options are
  • grep-v: It is a negative search. You can display the lines that are not matched with                 our search operation.
  • grep-n: Display line numbers
  • grep-h: Display file name.
  • grep-c: Count the number of matches.
  • grep-o-b: Display position of matches string
  • grep-L: Display file name that do not contain the pattern
  • grep-l: Case insensitive search
Examples of Grep Command
1. Search for string in a file
                               grep "name" file.txt                                             
This is the basic unix command. This searches for the string "name" in the file name file.txt. It displays all the lines contain with the word "name".

2.Search for a string in multiple files
                             grep "name" file1 file2                                          

3.Displaying lines before match
                          grep -B 2 "name" file.txt                                          
This will prints matched lines along with the two lines before matched lines

4.Displaying lines after match
                          grep -A 2 "name" file.txt                                          
This will prints matched lines along with the two lines after the matched lines

5.Count the number of matches
                            grep -c "name" file.txt                                            
Using this command find the number of lines that matches to the given string.

6.Display the line numbers
                             grep -n "name" file.txt                                           

7.Matching the lines start with a string
                               grep "^start" file.txt                                            
The symbol "^" shows that starting position of line

8.Matching the lines end with a string
                                grep "end$" file.txt                                             
The symbol "$" shows that ending position of line
Powered by Blogger.