I was wondering if there is a program in the common unix toolset such as grep th
ID: 657705 • Letter: I
Question
I was wondering if there is a program in the common unix toolset such as grep that instead of filtering the lines that contain a string, simply outputs the same input but highlighting or coloring the selected string.
I was thinking in doing it by myself (should be simple enough), but maybe it already exists as a unix command.
I'm planning in using it to monitor logs, so I would do something like this:
tail -f logfile.log | highlight "error"
Usually when I'm monitoring logs I need to find a particular string but I also need to know what is written before and after the string, so filtering sometimes is not enough.
Does something like that exist?
Explanation / Answer
You could use the grep -C flag which gives n lines of context, e.g. grep -C 3 will print the 3 lines before and after the match. There are also -B and -A for before and after.
If you are looking to highlight given strings regularly, e.g. specific log formats it might be worth using python pygmentize with a custom lexer, since it is regex based you will be amazed how easy it is. This latter also has the advantage of being cross platform although some terminals don't do colour very well.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.