This article will guide you to the grep
command. How to use grep
to print lines match a pattern. The grep
command is an extremely powerful command in Linux, especially when you use it in the pipeline.
Grep command syntax
Table of Contents
We have two ways to use this command.
First, we use this command to find for text patterns in the file.
$ grep pattern [file...]
Second, we use this command to find for patterns in the standard output of pipeline.
$ command-1 | ... | grep pattern | ... command-n
Example use grep to print lines that match a pattern
Example find a pattern in a file
First, we will do the example with the first use. We will find a pattern in a file, the grep
command will print the lines containing that pattern.
For example, we have the file with the following content, the file name grep-demo.txt
.
line 1 - writebash.com
line 2 - demo content 2
line 3 - my name is Danie Pham
line 4 - writebash.demo
line 5 - write.bash
Next, we will use grep
to print the lines containing the pattern writebash
.
$ grep writebash grep-demo.txt
line 1 - writebash.com
line 4 - writebash.demo
If you look at the image above, there is a line contain string writebash.com
and a line contain string writebash.demo
. Although two lines are different, grep command prints it all, because it contains a pattern writebash
.
If you want to find the line containing only the exact writebash
string, you add the -w
option to the command.
$ grep -w writebash grep-demo.txt
For help with grep commmand, you can type this command and read about all options:
$ grep --help
Example find a pattern in the pipeline data
Now, we will do an example of using grep in the pipeline.
I use a familiar example, listing all the files in the /bin
directory. And then, I will use the grep
command to find all files with word zip
in its name.
$ ls /bin | grep zip
bunzip2
bzip2
bzip2recover
gunzip
gzip
The data in the pipeline after processing through grep, can continue processing with another command.
Grep and regular expressions
Above, I only do simple examples with simple words. In fact, you will have to find much more complex patterns, for example: email address, email login information, etc.
To do that, you need to use advanced patterns and it calls regular expressions. In this article, I will not mention it, but can you find out more about regular expressions?
I will talk about regular expressions in the next article.
Conclusion
The grep
command is a really powerful command, probably all Linux users have to admit it. Find out more about it, it depends on you and how much you practice it.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).