Shell Script for grep with context display and highlighted pattern matches
Last Updated :
05 Feb, 2023
grep ( global search for regular expression and print out ) is a filtering command used for searching a particular pattern of characters in a file. It offers different options for manipulating the searched result, a brief description of these options can be found in this article.
General Syntax :
$ grep [option(s)] pattern [file(s)]
One of the options offered with the grep command is --color which highlights the searched pattern in color, making it more convenient for the user to recognize.
Example: Consider file.txt with the following content and pattern to be searched is "the"
Hello geek!
I am a demo file.
--color option can be used for highlighting the searched text.
Like this article, if you understood the concept.
Command:
$ grep --color 'the' file.txt
Output:
The output of the above Command
You can observe that it outputs only the lines which contain the searched pattern. But if we want to display the whole content with the highlighted pattern, we can use the OR operator in the pattern and pass a metacharacter as the second pattern. The two metacharacters which can be used here are ^ and $. ^ stands for the beginning of a text line and $ stands for the end of a line. Obviously, all the lines will have a beginning and end so all the lines will get printed without anything extra highlighted.
Command:
$ grep --color 'the\|^' file.txt
OR
$ grep --color 'the\|$' file.txt
Note: We are required to use the escape '\' character for escaping the OR operator so that grep won't consider the OR symbol '|' as part of the pattern. Alternatively, we can use the -E option to directly use the OR operator in the pattern and the command will look like this:
$ grep -E --color 'the|^' file.txt
OR
$ grep -E --color 'the|$' file.txt
Output:
Syntax Explanation :
General Syntax 1: $ grep --color 'pattern\|^' filename
- grep -> Filtering Command
- --color -> Highlights the searched Pattern
- pattern -> write the pattern to be searched, for multiple patterns use the escape and OR operator
- A metacharacter -> '^' meaning start of a text line or '$' meaning end of line
- filename -> name of the file or files
you can write multiple file names like [ $ grep --color 'pattern\|$' file.txt file2.txt ]
General Syntax 2: $ grep -E --color 'pattern|^' filename
Using the -E options you can directly use the OR operator in the pattern
Now after understanding how we can use the grep command, Let's look at the shell script implementing the same.
#!/bin/sh
echo "Enter the file name(s) : ";
read filename # reads the input and stores file name(s) in variable named filename
echo "Enter the Pattern : ";
read Pattern # reads the input and stores it in a variable named Pattern
grep --color -E "$Pattern|^" $filename # grep filters the pattern $Pattern in file with name $filename
# grep --color "$Pattern|\'$'" $filename
# Both LINE 6 and LINE 7 will produce the same Output
Output:
Code Explanation:
- We have asked the user to input the file name and stored it in a variable named $filename.
- Then we have taken the input for a pattern to be searched and stored it in another variable named $Pattern.
- Finally, we have passed the $Pattern and $filename in the grep command as we have learned above.
Conclusion
We have learned how to use the grep command for getting the highlighted text. Also, it can be concluded that grep directly does not offer any option to print the whole content with the highlighted pattern but we can use this trick of passing metacharacters as a second parameter along with the --color option in the grep command to get the required output.
Similar Reads
Shell Script to Displays All the Lines Between the Given Line Numbers
In this article, We will write a shell script to display all lines between given line numbers to console. We have a file name and start and end line, We have to write a script that will print all the lines from the specified start line to the ending line of the file. Example: File : a.txt Line 1 : H
2 min read
How to Use the grep Command in Linux with Examples?
Grep is a very powerful utility in Linux that is used for searching patterns within files or a stream of text. It's one of those essential tools that system administrators and developers use for parsing logs, cleaning up data, or otherwise dealing with large text apa. This tutorial will walk you thr
4 min read
Shell Script to Display the Exit Status Using Grep Command
Linux provides users a great cool feature of the command-line tool along with a graphical user interface where they can perform tasks via ruining command. All of this command returns a status according to their execution. Its execution value can be used for showing errors or take some other action i
4 min read
How to Create and Use a Syntax Highlighter using JavaScript?
A syntax highlighter is a tool that colorizes the source code of programming languages, making it easier to read by highlighting keywords, operators, comments, and other syntax elements in different colors and fonts. In JavaScript, you can create a syntax highlighter by either manually writing your
3 min read
How to get the Highlighted/Selected text in JavaScript?
There may be a need to find out the text selected/highlighted by the user. It can be done very easily using the window and document objects and their properties. Handling selected text is different for different browsers. The ways to get selected text are shown below: Method 1: window.getSelection p
2 min read
Shell Script To Show All the Internal and External Links From a URL
To make hierarchy among the webpages or the information web developers use to connect them all is called webpage linking. There are two types of webpage linking: one is internal linking, and the other is external linking. Internal links are those which link a page available on the same website to pr
4 min read
Run a Command Conditionally with netcat and grep
In this article, we will explore the combination of Netcat (nc) and Grep commands in a Unix-like environment to execute commands conditionally based on specific search criteria. Netcat enables network communication, serving as a tool for sending and receiving data across networks. Meanwhile, Grep ex
4 min read
Highlighting Search Results with Elasticsearch
One powerful open-source and highly scalable search and analytics web application that can effectively carry out efficiently retrieving and displaying relevant information from vast datasets is Elasticsearch. Itâs also convenient that Elasticsearch can highlight the text matches, which allows users
4 min read
Shell Scripting - Standard Input, Output and Error
Working on Linux applications we have several ways to get information from outside and to put it inside: command line args, environment variables, files. All of these sources are legal and good. But it has a finite size. Another way to establish communication is standard streams: input stream (stdin
7 min read
Working with Highlighted Text in Python .docx Module
Prerequisites: docx Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word docume
5 min read