Signup/Sign In

Grep Command In Linux

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

Grep With Pipe

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

Syntax:

command | grep <searchWord>

Example:

cat marks.txt | grep 9

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

Grep Without Pipe

It may be used without pipe as well.

Syntax:

grep <searchWord> <file name>

Example:

grep 9 marks.txt

Look at the above snapshot, the grep command accomplish the same thing as the previous example but without pipe.

Grep Options

grep -vM: The 'grep -v' command reveals lines not matching the provided term.

Syntax:

grep -v <searchWord> <fileName>

Example:

grep -v 9 marks.txt

grep -v 9 marks.txt

Look at the preceding snapshot, program "grep -v 9 marks.txt" reveals lines that don't include our search phrase '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

Look at the preceding snapshot, program "grep -i red exm.txt" reveals 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 preceding the result.

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

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

Syntax:

grep -A<lineNumber> <searchWord> <fileName>

grep -B<lineNumber> <searchWord> <fileName>

grep -C<lineNumber> <searchWord> <fileName>

Example:

grep -A1 yellow exm.txt

grep -B1 yellow exm.txt

grep -C1 yellow exm.txt

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



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.