-1

I thought this might be easy but not so much

I want to color the output of a command based on delimeters, in my case

apt-show-versions -u

and want to color the packages' names based on the colon seperator, or on the word 'to'. It seems to run into wanting a parser not a filter.

using color xterm on Linux and PuTTY

Robert Murphy
  • 149
  • 1
  • 11

1 Answers1

1

Others have been interested in similar functionality, I suggest you check the tools (grc/grcat) mentioned there.

You might be able to get away with sed-magic, though. I'm not sure what you want to colour exactly, and neither do I know what the output of apt-show-versions looks like, but this colours everything preceding a colon and the word "to":

cat << EOF | sed -e "s/^[^:]*/\x1b[31m&\x1b[0m/g" | sed -e "s/to/\x1b[31m&\x1b[0m/g"
foo: 1 to 2
bar: 3 to 4
quux: 5 to 6
EOF

You can paste that into a terminal and see if it's what you're looking for. Essentially, it searches for occurences of regular expressions and surrounds it with ANSI colour codes:

  • s/X/Y&Y/g : replace X by surrounding with Y, in the entire input (g flag), or, quoting man sed:

    s/regexp/replacement/
           Attempt to match regexp against the pattern space.  If  success‐
           ful,   replace  that  portion  matched  with  replacement.   The
           replacement may contain the special character & to refer to that
           portion  of  the  pattern  space  which matched, and the special
           escapes \1 through \9 to refer  to  the  corresponding  matching
           sub-expressions in the regexp.
    
  • ^[^:]* : from beginning of line, match everything until you encounter a :

  • \x1b : Hex 27, an escape sequence (see here for more!)
  • [31m : ANSI colour code for red
  • [0m : ANSI colour code for "reset to normal output"

If anything, this post taught me that sed captures matches in & ;-) Hope you gained some insight, too!

Oliver Baumann
  • 2,209
  • 1
  • 10
  • 26
  • Thank you tremendously Oliver, regexps are always a bit of a problem for me, this works great. I modified things a bit, here's the command and some output – Robert Murphy Oct 19 '18 at 23:10
  • 1
    # apt-show-versions -u | sed -e "s/^[^:]*/\x1b[33m&\x1b[0m/g" | sed -e "s/to.*/\x1b[32m&\x1b[0m/g" – Robert Murphy Oct 19 '18 at 23:30
  • The output looks like bsdutils:amd64/bionic-updates 1:2.31.1-0.4ubuntu3.1 upgradeable to 1:2.31.1-0.4ubuntu3.2 – Robert Murphy Oct 20 '18 at 00:07