What is the grep command in Linux?

The grep command is part of the GNU Core-utilities package and filters text files for a given character arrangement or pattern.

The GNU Core-utilities package is available on all Unix-like operating systems.

Arguments

The grep command supports many functionalities. Users can select a functionality of their choice by setting the right flags or arguments. In this shot, we go through the most frequently used arguments for grep.

grep -c “pattern” file.txt

The -c flag is used to output the number of lines in file.txt that contain the word pattern as a string or sub-string.

grep -i “paTTern” file.txt

The -i flag makes sure that grep performs a case-insensitive search. It displays all the lines in file.txt that contain the word paTTern, regardless of the alphabetical case as a string or sub-string.

grep -l “pattern” *

The -l flag outputs the name of all those files containing text with the word pattern in it as a string or sub-string.

grep -w “pattern” file.txt

The -w flag is used to output all those lines in file.txt containing pattern as a whole word and not as a sub-string.

grep -o “pattern” file.txt

The o flag displays only the matched pattern instead of displaying the entire string or line which contains it.

grep -n “pattern” file.txt

The -n flag outputs the line number of the lines containing pattern alongside the line itself.

grep -v “pattern” file.txt

The -v flags invert the search results, as it displays those strings in file.txt which do not contain pattern.

grep “^pattern” file.txt

The ^ operator is used to output all those lines in file.txt which have pattern as their first word.

grep --help

The --help flag is used to open the manual page of grep, which contains additional information about it.

Example

In the example below, we use the echo command to create a text file, and write Educative!, Edpresso, and Sadzub on lines 1, 2, and 3, respectively.

Subsequently, we use the -i flag to run a case-insensitive search for the sub-string EDUCative in our text file and print the string which contains it. Additionally, we use the -n flag to print the line number of the line, which contains EDUcative and zub.

Searching for Zub would not yield any results because the -n flag runs a case-sensitive search.

Last but not least, we use the -o flag to print the matched pattern itself, i.e., Educative.

Note that for the -o flag, there is no exclamation mark at the end of the output.

Terminal 1
Terminal
Loading...
Copyright ©2024 Educative, Inc. All rights reserved