Turambar
Turambar

Reputation: 313

Color specific words in Linux terminal whenever they appear

I have a bunch of scripts running in my terminal (and I don't have the ability to edit them) which output messages to the terminal. I would like my terminal to automatically color specific words in the output.

For example, some of the scripts output FAIL when a test fails. How can I configure the terminal to color this specific word, any time it appears, to be in a specific color (for example, red).

Upvotes: 26

Views: 21873

Answers (3)

JohnKollar
JohnKollar

Reputation: 21

To colorize the text output from a command one might try piping the output of the command into sed, such as the following:

yourcommand | sed -e 's/FAIL/^[[01;31mFAIL^[[00m/g' -e 's/SUCCESS/^[[01;32mSUCCESS^[[00m/g'

One could also place those substitution rules into a text file (e.g. colorize.sed) and use the following:

yourcommand | sed -f colorize.sed

This will allow different colors to be assigned to different match strings. Note that in my examples the '^[' means the escape character, not a carat followed by a square bracket. The escape character can be entered into the rule by typing Ctrl-V and then pressing the escape key.

The colors/effects that are available for these tty codes are as follows:

Foreground colors: Black=30, Blue=34, Cyan=36, Green=32, Purple=35, Red=31, White=37, Yellow=33

Background colors: Black=40, Blue=44, Cyan=46, Green=42, Purple=45, Red=41, White=47, Yellow=43

Effects: Normal=00, Bold=01, Dim=02, Underlined=04, Blinking=05, Reversed=07, Hidden=08

These can also be combined with a semicolon as I did (i.e. 01;31 to get bold red).

Note that the '^[00m' code is required to disable the previous color/effect, otherwise the color/effect will persist after the match string. Also note that some of the effects don't work (or work as I described) with some terminal emulators.

I hope that I'm not just repeating what someone else has already said, because I didn't read through the entire discussion thread.

Upvotes: 2

NetVicious
NetVicious

Reputation: 4037

If the grep command installed in your linux/unix flavour doesn't has the -P parameter you can use:

egrep --color "\b(place_here_what_you_are_looking_for)\b|$"

Upvotes: 0

Andrew Aylett
Andrew Aylett

Reputation: 40700

It's probably easier to colour the words yourself, rather than getting the terminal to colour them for you. If you can't edit the scripts that create the output, can you filter them through something else?

At the most likely to be available end of the scale you could pipe your output through grep:

tail -F logfile | grep --color -P "FAIL|"

This matches either "FAIL" or "", and highlights the matched portion of the string.

You could further use something more specialised, as described in this blog post, for example.

Upvotes: 20

Related Questions