Linux grep

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Linux grep

The 'grep' command stands for "global regular expression print". grep command filters the content of a file which makes our search easy.

grep with pipe

The 'grep' command is generally used with pipe (|).

Syntax:

command | grep <searchWord>

Example:

cat marks.txt | grep 9 

Linux Grep Filters1

Look at the above snapshot, grep command filters all the data containing '9'.


grep without pipe

It can be used without pipe also.

Syntax:

grep <searchWord> <file name> 

Example:

grep 9 marks.txt 

Linux Grep Filters2

Look at the above snapshot, grep command do the same work as earlier example but without pipe.


grep options

Syntax:

grep -v <searchWord> <fileName> 

Example:

grep -v 9 marks.txt 

Linux Grep Filters3

Look at the above snapshot, command "grep -v 9 marks.txt" displays lines hwich don't contain our search word '9'.

  • grep -i: The 'grep -i' command filters output in a case-insensitive way.

Syntax:

grep -i <searchWord> <fileName> 

Example:

grep -i red exm.txt 

Linux Grep Filters4

Look at the above snapshot, command "grep -i red exm.txt" displays all lines containing 'red' whether in upper case or lower case.

  • grep -A/ grep -B/ grep -C

    grep -A command is used to display the line after the result.

    grep -B command is used to display the line before the result.

    grep -C command is used to display the line after and line before the result.

    You can use (A1, A2, A3.....)(B1, B2, B3....)(C1, C2, C3....) to display any number of lines.

Syntax:

  1. grep -A<lineNumber> <searchWord> <fileName>  
  2. grep -B<lineNumber> <searchWord> <fileName>  
  3. grep -C<lineNumber> <searchWord> <fileName>  

Example:

  1. grep -A1 yellow exm.txt  
  2. grep -B1 yellow exm.txt  
  3. grep -C1 yellow exm.txt 

Linux Grep Filters5

Look at the above snapshot, command "grep -A1 yellow exm.txt" displays searched line with next succeeding line, command "grep -B1 yellow exm.txt" displays searched line with one preceding line and command "grep -C1 yellow exm.txt" displays searched line with one preceding and succeeding line.