Bash grep Command

MD Aminul Islam Jul 12, 2022
Bash grep Command

Sometimes we need to search for specific keywords, phrases, or patterns in files like logs, texts, etc. This article will show how we can find specific keywords, phrases, or patterns in files using a single-line Bash script.

Also, we are going to discuss the topic with relevant examples and explanations.

the grep Command in Bash

For searching a specific keyword, phrase, or pattern in a file, there is a specialized command in a Bash script, grep. We can use this command to display the lines before and after the keyword matched in a specific file.

This command uses flags like -A, -B, and -C. We will see the use of these below.

Below shared the example that uses the normal grep keyword.

$ grep 'KEYWORD' /YourPath/to/file.txt

In the example above, we are looking for the word KEYWORD on the file name file.txt. After running the command, you’ll get an output with the content of the file where each of the matches is marked.

$ grep -B 4 'KEYWORD' /YourPath/to/file.txt

In the newly updated example above, we are looking for the word KEYWORD on the file name file.txt. But the difference is that we used a flag -B 4, which tells the command to show the 4 lines before the matches.

After running the command, you’ll get an output with the content of the file where each of the matches is marked.

$ grep -A 2 'KEYWORD' /YourPath/to/file.txt

In our last example, we look for the word KEYWORD on the file name file.txt. But the difference is that we used a flag -A 2, which tells the command to show the 2 lines after the matches.

After running the command, you’ll get an output with the content of the file where each of the matches is marked.

Another flag that can be used with this command is --color. The purpose of this flag is to provide color on the matches found.

Please note that all the code used in this article is written in Bash. It will only be runnable in the Linux Shell environment.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn