Grep Command in Linux: Search Specified Strings in Text Files
Developers are usually attracted to the Linux operating system because they can achieve their goals in an easier way and perform their tasks efficiently by familiarizing themselves with Linux commands. Linux offers a variety of helpful commands so that users can have the best performance in managing their projects; the world of Linux is not complicated but exciting.
Maybe no one has told you that if you master the comprehensive Linux commands and get to know the most used commands of Linux, you will have a new experience of using Linux. For this reason, we always recommend to Linux beginner users who have recently purchased a Linux VPS or are planning to purchase a Linux VPS, to master Linux commands to understand the difference between the Linux OS and other OSs and enjoy the performance of Linux in managing their projects.
Have you ever looked for a way to find a string of specified characters in text files in Linux but don’t know how to find it??
The grep command was designed to answer this need. The grep command is one of the most widely used and basic Linux/Unix command line tools designed to perform search operations in files and texts.
In this article, we will teach how to use the grep command in the Linux system to search for words or strings in a specific text file. I can see the enthusiasm of using the grep command in your eyes and I will not keep you waiting for the wonderful world of Linux more than this, so let’s go to get acquainted with a new Linux command.
What is the grep command?
Grep stands for Global Regular Expression Print. grep is a widely used Linux command line tool that belongs to the family of egrep and fgrep tools. The purpose of running the grep command is to search for a string of specified characters and words in a specified text file.
In other words, the grep command is a powerful file searcher that finds the text file containing the entered phrase according to the words and strings you enter. grep, which is a command to find patterns in texts, is provided by default with all Linux versions. But if for any reason this efficient tool is not installed on your Linux, you can easily install it through your Linux package management repository.
In response to where did grep originate from? we must say that grep belongs to the egrep and fgrep family of tools and is derived from a special command for a very simple and practical Unix text editor called ed. The grep command greatly facilitates the tasks of managers and developers, especially in the review and search of large report files, the advantage of this command becomes visible. In the following, we will teach the most common grep commands for different purposes.
What is fgrep?
Understanding the function of different Linux commands will help you avoid using them interchangeably and execute the right commands for your purposes. Some users use fgrep instead of grep and some don’t know the difference between these two commands. fgrep is different from grep, fgrep stands for Fast Global Regular Expression Print, as the name suggests, it is a fast algorithm to search for a text pattern with fixed characters in the file, using which you can search for a pattern that matches fixed strings, while grep helps you search for complex expressions.
The fgrep command allows you to search multiple files in the File parameter and find the file that contains the line matching the constant string algorithm you want. The fgrep command interprets all characters such as $, *, [, |, (,) that have a special meaning for the shell.
What is the difference between grep and find?
The find command, which we have already discussed, is used to locate files and directories based on various criteria such as permissions, size, name, etc. The Find command checks the directory hierarchy based on the specified criteria and recursively searches for files and directories.
The function of the grep command, which should have been revealed to you by this article, is used to search for complex and regular patterns in the content of files. Using the grep command, the files are checked and the line that matches your defined pattern is printed. Therefore, the purpose of using grep is different from find. Using grep, the content of the file is searched to find text patterns, while the find command is executed to locate files and directories based on various criteria in the directory hierarchy.
The grep command displays lines that match a specific pattern and is useful in extracting information, but the find command, in addition to locating files, allows you to perform actions on files, such as deleting files, changing permissions, and executing commands.
How to use the grep command in Linux
Searching for a specific string or word in a file
The simplest grep syntax to find a specified string or words in a specified text file is as follows:
grep "string" file name
OR
filename grep "string"
For example, if you have a text file called samplefile.txt and you want to search for the word “Linux “in it, you should enter the following command:
grep "Linux" samplefile.txt
Output:
Linux is an open-source operating system that is mostly used by developers. Linux also has different distributions, each of them with unique features to meet the needs of users.
The previous command searches for the word Linux in the text file samplefile.txt along with the lines that contain the word Linux. You can combine different options with this command to achieve your goal.
If the desired text file is stored in a different file path, it will be necessary to specify the file path when running the command. For this purpose, you must run the following command:
grep "string" /path/to/file
Note that when running grep commands, pay attention to the uppercase and lowercase letters of the string or word you are searching for, because the grep command is sensitive to uppercase and lowercase letters.
Searching multiple files to find a specific string
In addition to checking a text file, you can check several files to search for a specific word or string. For this purpose, you can search for the desired string in several files by separating the file names with a space. For example, if you want to search for the word Linux in the text files Test1, Test2, and Test3, you must enter the following command:
grep Linux Test1 Test2 Test3
Output:
Test1: Linux operating system number 1
Test1: Linux is an open-source operating system that is mostly used by developers.
Test2: Linux Operating system number 2
Test2: Ubuntu Linux Operating system number 2
Test3:Linux operating system number 3
Test3:Ubuntu Linux Opersating system number3
The output of this command displays the files and lines that contain the word Linux. Fortunately, you don’t have a limit on the number of files in the execution of the previous command, you can check any number of files with the use of the previous command.
Searching in all the files in the directory
If you want to check all the files in the directory to find a string of specific characters, you should use the * symbol in the last part of the grep command. For example, to search for the word” Linux” in all the files in the directory, you must enter the following command:
grep Linux *
The output of this command, like the previous, grep commands, displays the file name and the line that matches this word.
Exact Matching word search in files
Adding the-w
flag to the grep command finds the exact word in the files in the directory and prints the file name that contains the exact word and the lines that match the word exactly. For example, if you want to search for the word “opensource” in the text file samplefile.txt, you must enter the following command:
grep -w "opensource" file.txt
Output:
Linux is free and opensource operating system.
To find the word “opensource“, if you only search for the word” Open“, you will not get a result because this command is used to find the exact word.
If you want to search Opensource in the files in the directory:
grep -w opensource *
Searching for a string in all directories and subdirectories recursively
If you want to search for a string in all subdirectories and directories, you must run the grep command in combination with the-r
flag. The syntax of this command is as follows:
grep -r "string-name" *
For instance:
grep -r "Linux" *
Output:
Desktop/files/Test2: If you are thinking of a fast and advanced OS, choose Linux
Desktop/files/Test1: welcome to Linux!
samplefile.txt: Linux is free and opensource operating system.
samplefile.txt: Linux also has different distributions, each of them with unique features to meet the needs of users.
You can also use the commandgrep -rw "Linux" *
to find exact words in all subdirectories, existing directory files, and their exact path, which displays the same output as the commandgrep -r "string-name" *
.
Finding a string by colorizing it in the content of the files
If you want to find the desired pattern or string in the contents of the files more easily, the best filter is the colorizing of the desired string you are looking for. To colorize the string or word you are looking for, you can run the following command:
grep --color "Linux" file.txt
Output:
Linux is an open-source operating system that is mostly used by developers. Linux also has different distributions, each of them with unique features to meet the needs of users.
Disabling case sensitivity of the grep command
When you search for the word Linux in the files in the directory, you will get the desired results because the exact of the “Linux” (according to the first capital letter of the word) is present in the content of the file and it will be found in your search; but if you want to search for “linux“, you will not get the output you want. Because the “linux” starts with a small letter and there is not” linux” in the contents of the files, but there is” Linux“. In order to ignore Uppercase and lowercase letters when searching by the grep command, you must combine the-i
flag with it and run the following command:
grep -i "linux" file.txt
By adding the-i
flag to the grep command, the lines that contain the word Linux in file.txt will be displayed regardless of the uppercase and lowercase letters of the word.
Reverse search using grep
Until this part of the article, the grep command was used to search for the string or word you want in the files in the directories, but you can also use the grep command to find files or lines that do not match your particular string or pattern. For example, to reverse search the word “Linux” in samplefile.txt, enter the following command:
grep -v "Linux" samplefile.txt
In the output of the previous command, you will see lines that do not contain the specific phrase or word that you specified.
Counting the number of lines that contain the word you search
If you want to know how many lines in your text file contain your specific phrase, you should use the following command:
grep -c "Linux" sample file.txt
Output:
2
To count the lines containing the word Linux in all the files in the directory, enter the following command:
grep -c Linux*
Output:
Test1:2
Test2:2
Test3:2
samplefile.txt:2
Numbering the lines that contain the word you search
By executing the grep command and the -n flag, you can number the lines that contain the specific phrase you want in a list. for example:
grep -n "Linux" file.txt
Output:
1: Linux is an open-source operating system that is mostly used by developers.
2: Linux also has different distributions, each of them with unique features to meet the needs of users.
Creating a list of file names containing specific terms
Sometimes you are looking for files that contain a specific phrase or string, in this situation the grep command will help you and by running the following command you can access a list of file names that contain your specified phrase:
grep -l Linux*
searching for a line that exactly matches with the special string
Usually, by running the grep command, you would see entire the lines that contain the phrase or string you search, but now you can use the grep command and-x
flag to search only the lines that have an exact match with the string you want. That is, in the output of this command, the phrase you did not search for will not be displayed and Apart from the character you specified, you will not see any other characters. To search for the term” Linux Operating system“, you must enter the following command:
grep -x "Linux operating system" *
In running the previous command, it is important to use quotation marks, so don’t forget. When searching, if you have used space or a symbol, be sure to type quotation marks.
REGEX search using the grep command
REGEX stands for REGULAR EXPRESSION, which is a pattern of characters that describes a sequence of strings to match a specific pattern. For a better understanding, consider the following examples:
- ^: Matches the first character of a line.
- $: Matches the last character of a line.
- “.”: Matches all characters.
For example, if you want to search for lines starting with a specific character, you should enter the following command:
grep ^character file_name
For example, to find the lines that start with the letter d in the sample file.text, enter the following command:
grep ^d samplefile.txt
Output:
distributions such as Ubuntu,Mint, Fedora.
developers prefer Linux VPS for various purposes because it is an advanced, free and open source operating system that meets the needs of most users.
achieving specific output using Pipes and the grep command
You can also use Pipes in the grep command to get unique output. For example, to check whether the desired package is installed in your Ubuntu system or not, you can run the following command:
dpkg -L | grep "package-name"
Displaying the number of lines before and after the search string
The command you will learn in this part of the article is to provide more information in the search results. By accessing the lines after or before the string you are searching for, you can better understand the meaning of the phrase and choose the phrase that is more relevant to your purpose.
To see the lines before the search string use-B
, to access the lines after the search string use-A
, and to see the lines before and after the search string use-C
. For example, to view the 2 lines before and after the Linux search string, run the following command:
grep -C 2 Linux
In the output of the previous command, in addition to the line containing the word” Linux“, you will see 2 lines before and after the “Linux“.
You can also run this command using Pipes, as in the following example:
ifconfig | grep -A 4 ens3
By running this command, it displays 4 lines after the ens string.
Limiting the output of the grep command
Running grep for your desired search pattern may result in long results that confuse you, so you can limit the number of lines that contain your search string. For example, if you want to access the 3 lines that contain your search string (for example Linux), you must enter the following command:
grep -m3 Linux
The output of this command prints the first three lines that contain the word Linux. You have not specified a file in this command, so the result of this command displays the first three lines that contain the word Linux in each file with the name of the file.
Filename search
The grep command allows you to search for text files with the desired extension, to search for a list of files with a specific extension in the desired directory, execute the following command. For example, to find a list of files. xhtml in the ~/example directory, enter the following command:
ls ~/example / | grep ". xhtml "
To access a list of files with the. xhtml extension in the current working directory, run the following command:
ls | grep " . xhtml "
Filtering phone numbers in files
The grep command is also helpful for finding and filtering phone numbers in text files. You should use grep regular expressions to filter the phone number. The following example is a good guide for filtering phone numbers via the grep command:
grep '\(([0-9]\{3\})\|[0-9]\{3\}\)[ -]\?[0-9]\{3\}[ -]\?[0-9]\{4\}' test-file
You need to change your pattern based on your desired phone number.
Finding email addresses
With the help of the grep command, it is easy to find email addresses in text files. By searching for regular expression patterns in text files, you can also search for email addresses:
For example:
grep '^[a-zA-Z0-9]\+@[a-zA-Z0-9]\+\.[a-z]\{2,\}' test-file
Searching for URLs in the source file
The grep command gives you the power to find URLs in certain text files. To access a list of URLs in a text file, use the following example:
grep -E "^(http|https|ftp):[\/]{2}([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4})" test-file
In the output of the previous command, a list of URLs in the test-file is displayed.
Pattern search in compressed files
Using the zgrep command, you can check the compressed files to search for the pattern you want. For this purpose, you need to make a compressed archive of your test file:
gzip test-file
Then use the following command to search for text expressions or the pattern you want (pattern ) in the created archive:
zgrep pattern test-file.gz
FAQ
Should we install grep?
Fortunately, grep is installed by default in all Linux distributions and you don't need to install grep.
When running the grep command, should special characters be used?
Characters such as quotation marks or metacharacters such as (& ! . * and \) each have different meanings in the system, which should be typed in the command according to the syntax you use. Especially the quote character that must be typed when entering the regular expression in the grep command.
Conclusion
We reach the end of the article with complete knowledge about the grep command. Now you have become a professional Linux user who knows how to use the grep command for your various purposes. This article changed the perception of users who thought the use of the grep command was complicated and guides you on how to use the grep command efficiently to facilitate your tasks. If you need more information about the grep command than in this article, run thegrep --help
command.
The grep command provides useful and distinct results with different options and helps you in finding the phrase you want.
We hope that reading this article was useful for you.