grep command in Unix/Linux with examples

The grep command used to search the characters or lines for a particular format in the file and printing the matching lines to the standard output.

grep command syntax

grep <options> pattern <files>

Lets assume the below file as input to the grep command

$cat > sample.txt

There are many useful commands present in the unix.
Few of the commands helps to search the string in the file.
The Unix is one of the popular operating system in the world.

Case insensitive search:

The -i option enables the grep to search the string case insensitively. The below command search the Unix string in the file and prints the lines which has both “unix” and “Unix”.

Example : grep -i “Unix” sample.txt

Output :

Output of grep – i

To print number of lines after the string match:

The grep with the option -A helps to print the number of lines after the string match.

Example : grep “search” sample.txt -A 1

Output:

Output of grep -A

To print number of lines before the string match:

The grep with the option -B helps to print the number of lines before the string match.

Example : grep “search” sample.txt -B 1

Output:

Output of grep -B

Print the non-matching lines

The grep with the option -v is used to print the non-matching lines.This will print all the lines that do not matches the pattern.

Example : grep -v “Few” sample.txt

Output:

Output of grep -v

Print the matched lines with line number

The grep with option -n is used to print the matching lines with line number where the searching string present in the given file.

Example : grep -n “Few” sample.txt

Output:

Output of grep -n

Search the string recursively inside the directory

The grep with option r will perform its search recursively.If it encounters directory,it will traverse inside the directory and continue the search on the files.

Example : grep -r “Few” test_dir

Output: