December 2, 2019
December 2, 2019
Linux operating system based servers usually have no graphical interface for security reasons. In this case, it becomes very important to know and know how to manipulate the Linux terminal.
A very useful operation that we can perform with the terminal is searching inside a text file. Above all, if we work with configuration files of services like NTP.
In this post, we will teach you how to use the grep command in Linux (Unix), and reinforce the learning with a useful example for your daily workflow.
The grep command belonging to the Unix family is one of the most versatile and useful tools available. It looks in a text file for a pattern that we define. In other words, with grep you can search for a word or pattern and the line or lines that have it will be printed.
At first sight, it can be a command of little utility, however, sysadmins that handle many services with various configuration files, use it to query or search for specific lines within those files.
First, connect to the VPS using SSH. Here’s an article that shows how to do it using PuTTY SSH.
If you’re running Linux on your computer, just open a terminal.
The grep command syntax when searching for a single file looks like this:
grep [options] pattern [FILE]
You can see the documentation and explanations of various options by executing this command in the command line:
As you can see there are many possibilities that the command offers us. However, the most important and commonly used options are the:
Let’s look some practical examples of the grep command.
To search for a word in a text file, just type the command:
grep query file
In our case, we’re looking for the word command in a file called grep:
grep command grep
The output highlights the lines that match the query like this:
To do this, it is necessary to add the option -i.
grep -i query file
That’s it, simple as that!
Using the grep command you can find out how many times a word is used in the text file. Just add the option -c.
grep -c query file
So far we have pointed out examples where we search for one word. Grep supports multiple queries in a single command. The command would look like this:
grep query1 file | grep query2 file
The command works in a very simple manner. First, we search for Query1 and then we pass through the pipe to a second grep command for the second word – Query2.
It is also possible to search a set of files in a single command:
grep -l word_to_search ./*
In the terminal, the files that have the word you searched for will be displayed in the output.
Using the grep command can make work much easier if we work with a lot of text files. That’s why grep is considered a very versatile command with many possibilities of use.
In this post, you learned what are the most common functions of the Linux grep command. On the other hand, we recommend you consult the official documentation to broaden your knowledge of it! Happy developing.