I'm using this to color the output of a script/command:
commandWithOutput | sed -r 's/(pattern)/'"${COLOR_RED}"'\1'"${COLOR_DEFAULT}"'/g'
(This will color all occurences of string "pattern" in the command's output.) And it works fine with traditional commands. However, if the script/command overwrites lines in its output (maybe this has more to do with a terminal/console than just standard output?), e.g.:
Building project X:
CXX Building file XYZ.cpp... [123/1034]
the behavior isn't as expected. My sed will still color the output but the overwriting doesn't work anymore, i.e.:
Building project X:
CXX Building file ABC.cpp... [1/1034]
CXX Building file DEF.cpp... [2/1034]
CXX Building file GHI.cpp... [3/1034]
CXX Building file JKL.cpp... [4/1034]
CXX Building file MNO.cpp... [5/1034]
// and so on...
CXX Building file XYZ.cpp... [123/1034]
Is there a way to color the output of a script/command that overwrites lines?
I've tried several different ideas ...
IFS=$'\r'+ OP'ssedcommand ... trying to use an intermediate pipe (mkfifo) for processing the output fromcommandWithOutput... a few attempts at trying to unbuffer stdout and/or stdin ... but (so far) could only get aawksolution to work, so fwiw ...NOTE: I'm assuming OP's command is generating a
\rwhen overwriting a line; if this is not the case the OP can try piping their command's output to| od -cto see what character is at the 'end of the line', with the idea being to use said character in place of my\rreferences (below).First we'll write a small script to generate some data, (re)printing over the first few lines, and then printing some 'standalone' lines:
Running the above generates the following output:
Running this through
odshows the\rat the end of the first 3 lines:We'll now look at one
awksolution for recoloring a specific pattern in the output from ouroverwritescript ...First we'll define the start and clear/reset variables for our desired color; for this exercise I'm going to use 'red':
NOTE: There are a few ways to define these colors (and the disable/reset); I'll leave that up to the reader to pick what works best in their environment.
Here's one
awksolution I found that works:Where:
-v ptn="test"- we want to recolor all instances of the stringtest; we'll pass this in asawkvariableptn-v cstart="${myred}"- assign our highlight color code (red) to ourawkvariablecstart-v creset="${myreset}"- assign our color clear/reset code to theawkvariablecreset-v RS="[\n\r]"- redefine our input record separator as either\ror\nsub(ptn,cstart ptn creset)- replace all instances oftestwith<red> + test + <reset>printf $0 RT- print our new line;RTallows us to make use of the sameRSthat was used to parse out this recordRunning the above generates: