Ale
Ale

Reputation: 19

How to add colors with a pipe?

I want to pipe the output of a command to something able to color the occurrences of a specific word.

Example: echo "ABC DEF GHI" | magic_color_thing("DEF") should print out ABC DEF GHI with DEF colored.

I want to do it with ZSH and I want to preserve all the lines as well as the carriage returns.

Thank you in advance for any help!

Upvotes: 2

Views: 1235

Answers (2)

If you have (a recent version of) GNU grep, use its --color option. To have it print non-matching lines as well, use a pattern that matches the empty string.

… | grep --color -E '|DEF'

If you want to do it entirely within zsh, make it iterate over the lines, surrounding DEF with color codes.

autoload colors; colors
while IFS= read -r line; do
  print -r -- "${line//DEF/$fg[red]DEF$fg[default]}"
done

See also How to have tail -f show colored output, and a few other questions tagged color.

Upvotes: 4

benosteen
benosteen

Reputation: 1366

Does

echo "...... DEF....." | grep --color "DEF"

do the job for you?

It would help if you said more about the kind of data you were piping in.

(And also whether lines without matches are important or not)

Upvotes: 3

Related Questions