I have a script that spews out i/o data with >>> and <<< symbolising direction - either input (<<<) or output (>>>).

<timestamp> >>>>>>>>>>

<timestamp> <<<<<<<<<<

I'd like to take this output and colorize the input with one color and the output with another - sort of like how git diff colors the differences in file versions.

How can I do this with the least amount of typing and preferably as a one-liner?

2 Answers 2


Maybe something like this with awk works for you:

awk 'BEGIN{ce="\033[0m"}
     {print cs$0ce}' your.data

That is:

    ce = "\033[0m"
/>>>/ {
    cs = "\033[1;31m"
/<<</ {
    cs = "\033[1;32m"
    print cs $0 ce
  • Or awk '/>>>/{s=1}/<<</{s=2}$0="\33[1;3"s"m"$0"\33[m"' to reduce the typing further. Apr 27, 2017 at 10:15
  • Wow - that was quick. Can't even begin to decipher exactly how that works, but it's exactly what I was after. If possible and you've got time to spare, please educate me.
    – AnthonyK
    Apr 27, 2017 at 12:34
  • @AnthonyK, that's actually quite straightforward awk. The basic syntax is /pattern/ { action }, the action is executed on lines matching the pattern. Then it's just setting variables with the escape codes for the colors, and printing out those and the line itself ($0).
    – ilkkachu
    Apr 27, 2017 at 12:57
  • @ilkkachu: got it. I was thinking that the variable s gets reset on each run. But I now understand that once set, it holds until the logic requires it to change. Is it possible to toggle the variable on each occurrence of a certain keyword instead of looking for different markers (that ones now easy)?
    – AnthonyK
    Apr 27, 2017 at 20:32
  • Answered my own question - awk 'BEGIN {s-0};/keyword/{s+=1}{c=s%2+1}$0="\033[1;3"c"m"$0"\033[0m"'
    – AnthonyK
    Apr 28, 2017 at 2:32

In the interests of all-shell, terminal-independent, semantic solutions, here is another way to do colors that utilizes tput, which uses the terminfo database to provide the correct color changing sequence for whatever terminals it recognizes:

black=$(tput setaf 0)
red=$(tput setaf 1)
green=$(tput setaf 2)
yellow=$(tput setaf 3)
blue=$(tput setaf 4)
magenta=$(tput setaf 5)
cyan=$(tput setaf 6)
white=$(tput setaf 7)
off=$(tput sgr0)

echo ${red}some red text${blue} some blue text${green} and green${off} and back to normal.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .