Very often I get some help information with the --help
flag of a command, which gives the output at the terminal like:
$ vmtkimagereader --help
Creating vmtkImageReader instance.
Automatic piping vmtkimagereader
Parsing options vmtkimagereader
vmtkimagereader : read an image and stores it in a vtkImageData object
Input arguments:
-id Id (str,1); default=0: script id
-handle Self (self,1): handle to self
-disabled Disabled (bool,1); default=0: disable execution and
piping
I want to syntax highlight the output like the upper half of the link (sorry that I can only post 1 link). I have tried highlight and pygmentize. However, highlight needs to specify a syntax, and pygmentize rendered the output as a wrong style (in the lower half of the link).
I'd like to know if there is a method to make the syntax highlight like this. Do I need to specify a style for pygmentize? Or do I have to turn to another solution?
Thanks!
ANSI escape strings
Using ANSI escape sequences to achieve what you want, you can create a format string (represented by prepended
\e[
and appendedm
) where38;5;{0..255}
is the 256-color of the text (0..255
being the range of available color codes), and48;5;{0..255}
is the 256-color of background. E.g.,will print black text (color code
0
) with a white background (color code255
). Note with theecho
command it requires the extended mode (toggled by the-e
flag) to interpret the ANSI escape string.Note the trailing
\e[0m
to unset the coloring, otherwise all text printed after this command withecho
will retain the format.\e[0m
resets it.Note an interesting use case that causes an error also. Placing an exclamation point before the ending
\e[0m
causes this output:That's because
!
is part of string expansion for Bash. See more on this SO question here. To make that work as expected we need to do:as single-quotes do not get expanded.
How to print every available color using ANSI escape sequences.
Save these in a file called
color-functions.sh
:Then, in another file, call the functions after you've
source
'd them:Here's a function that does both... But I think it's overkill because the output is far too large (256 * 256 = 2^16 combinations will be outputted):
Your use case
To color certain things certain colors, we can use
egrep -i
(-i
flag is case-insensitive) and theGREP_COLOR
variable:Or we could be real clever and functionise this:
Then: