Finding content in Linux - grep command

  • Last updated: Oct 12, 2024
  • Views: 9
  • Author: Admin
Finding content in Linux - grep command

Hello colleagues.

In today's article, we will show you how you can search for content in a file using the grep command. grep is a command that matches a (pattern) regular expression.

 

We will demonstrate the grep commands to the robot in a text file that we created called grep.txt in which we entered text information.

linux command grep


 

grep command syntax:

$. grep "string" filename

or

$. filename grep "string"


 

Example 1.

Search for the string containing the word core.

$. grep 'core' /root/grep.txt

linux command grep

As you can see, the grep command not only searches for and finds the 'core' substring in a file, but also displays all the lines in which this substring occurs.


 

Example 2.

Search is case insensitive. We execute the grep command with the -i option, which allows you to search for a case-insensitive line in the given file.

$. grep -i 'linux' /root/grep.txt

linux command grep

As you can see, as a result, we first tried to find the linux line without a parameter and the command returned an empty result to us, and with the use of the -i parameter we got a positive result.


 

Example 3.

Show the number of matches. To count the total number of lines in which the search string appears or is located, we need to specify the -c option.

$. grep -c 'system' /root/grep.txt

linux command grep

In the example, we wanted to find out how many lines the string (template) system is in, and as a result, we found out that the word system is in three lines.


 

Example 4.

Search for matches in the whole word. By default, the grep command searches a string for a character order match, but in this example we want to match a whole word. For this task, we need to use the -w option.

$. grep -w 'sys' /root/grep.txt

linux command grep

As you can see, as a result, the whole word sys is not in our text.


 

Example 5.

For convenience, you can make it so that more line numbers are shown, for this you need to specify the -n parameter.

$. grep -n 'sys' /root/grep.txt

linux command grep


 

Thank you all, I hope my article was of some help to you.

 

SIMILAR ARTICLES