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?


| improve this question | | | | |
  • software recommendations are explicitly off-topic per help center (it's the same here as at Stack Overflow). See meta.programmers.stackexchange.com/questions/6483/… – gnat Dec 5 '14 at 7:35
  • 1
    Wops, sorry this was an off-topic question. I'm going to try my luck on software recommendations then. – ordago Dec 5 '14 at 7:44
  • @gnat - It is more a programming question than a software recommendation. A better place for this question would be SO or UNIX SE. – mouviciel Dec 5 '14 at 8:33
  • 1
    @mouviciel If you are asking how to do it with existing tools, it' a unix question. If you are asking for a tool to do it, it's a software recommendation question. – user40980 Dec 5 '14 at 8:58
  • @MichaelT: Both are present in the question: I was thinking in doing it by myself => Unix question; maybe it already exists as a unix command => Software recommendation. – mouviciel Dec 5 '14 at 9:04

I would use a simple sed substitute command with ANSI escape codes put before and after the matching RE.

tail -f logfile.log | sed 's/\(error\)/^[[42m\1^[[0m/g'

where ^[ is an ESC character that you can obtain by pressing ctrl-V ESC

If you do need a highlight command, you can define it as a shell function:

highlight() { sed 's/'"$1"'\)/^[[42m\1^[[0m/g' ; }
| improve this answer | | | | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.