3

I am modifying the text following tail -f.
I have the following program that monitors a file:

tail -vf -c5 /tmp/index                         \
    | cat -n                                    \
    | sed s/^[^0-9]*\\\([0-9]\\\)/__\\\1__/g -  \
    ;

The sed successfully changes tail's output.
From another terminal i can now do:

RED='\033[0;31m';
NC='\033[0m';
printf "I ${RED}love${NC} Stack Overflow\n" 1>>/tmp/index;

And the tail monitoring program will display the update, in color.

But what I want, is the sed program, to add by itself, colors to the output. I have tried a bunch of different setups but to no avail. Mostly involving adding backward slashes here and there.

How do I have the tail-sed program, add colors to the output?

john-jones
  • 1,736
  • How would it add the color? To what? Can you give us an example input file so we can understand what the sed is doing (looks like you are changing the first digit after 0 or more non-digit characters to be surrounded by ___, is that right?) and then what color you want to add. Do you want to color those numbers? By the way, you can simplify your sed to sed 's/^[^0-9]*\([0-9]\)/__\1__/, no need for so many escapes if you quote, and the g is pointless with anchored regex (^), or even sed -E 's/^[^0-9]*([0-9])/__\1__/ if your sed has -E. – terdon Nov 22 '23 at 17:45
  • Yeah the cat -n is adding numbers to the tail but I want the numbers to be of a different color. I would like to add the color to the output from the tail program. And the only way I know to add colors in this context is the printf im showing and I'm guessing its somehow possible to add them the same way to the tail output. – john-jones Nov 22 '23 at 17:50

2 Answers2

6

I wrote a little script years ago that adds colors based on an input regular expression. I have posted it before here. If you paste that script into a file named color in a directory in your $PATH and make it executable, you can do:

tail -vf -c5 /tmp/index | 
  cat -n  |
  color -l '^\s*\d+'

Or, more manually:

tail -vf -c5 /tmp/index | 
  cat -n  |   
  perl -pe 's#^.*?\d+#\x1b[31m$&\x1b[0m#;'

Or, in sed:

tail -vf -c5 /tmp/index | 
  cat -n  |   
  sed -E 's#^[^0-9]*[0-9]*#\x1b[31m&\x1b[0m#;'

Or you could just do the whole thing in perl:

tail -vf -c5 /tmp/index |    
  perl -pe 's#^#\x1b[31m $. \x1b[0m#;'
terdon
  • 242,166
2
tail whatever | cat -n | grep -E '^[ 0-9]+' --color

would color the line numbers.

Ed Morton
  • 31,617