hgrep: Highlighted grep Script
Ever want to find text in a large file easily? The larger the text file, the more you will appreciate this shell script. We can use reverse video in shell scripts for more than just making pretty menus. What about highlighting text in a file or in a command's output? In this chapter we are going to show an example of using reverse video in a shell script that works similarly to the grep command. Instead of displaying the line(s) that match the pattern, we are going to display the entire file, or command output, with the matched pattern highlighted in reverse video. I like to call this hgrep.
In the process of creating this shell script, an initial test script was developed that ended up being very complicated. It started by grepping each line for the specified pattern. If the pattern was found in the line, then a scan of the line, character by character, was started to locate the exact pattern in the line for highlighting, then we grepped again for the pattern in remaining lines of text, and so on. This initial code had quite a few problems, other than the complicated nature of the script, caused by UNIX special characters making the output do some very interesting things when scanning shell script code. Regular text files worked fine, but the script was very slow to execute.
Then there was the revelation that the sed command should somehow be able to handle the pattern matching — and do so a lot faster than parsing the file with a shell ...