Finding content in Linux - grep command
- Last updated: Nov 3, 2023
- Views: 152
- Author: Admin
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.
grep command syntax:
$. grep "string" filename
$. filename grep "string"
Search for the string containing the word core.
$. grep 'core' /root/grep.txt
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.
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
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.
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
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.
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
As you can see, as a result, the whole word sys is not in our text.
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
Thank you all, I hope my article was of some help to you.