How to print control characters with escape sequences?

I have defined the color red using tput

red=$(tput setaf 1)

to colorize warnings in my program. This works fine:

printf '%sfailn' "$red"
# prints 'fail' in red

But on one occasion I would like to print out the escape sequence as-is, something like:

E[31mfail

How would I do this? I know printf has a %q flag but it escape others stuff I don’t want to.

Asked By: helpermethod

||

You can use printf directly, eg

printf "33[31mfail"
Answered By: X Tian

Sounds like you want the opposite of printing them literally, you want those escape characters converted to a printable descriptive form like E or 33, ^[

If it’s just the ESC (0x1b) character you want to convert to E, then with ksh93, zsh or bash (typically, the same ones that also support that non-standard %q), you can do:

printf '%sn' "${red//$'e'/\E}"

Or pipe to sed $'s/e/\\E/g'

For a more generic approach at converting non-graphical characters, you can use:

$ printf %s "$red" | od -A n -vt c # POSIX
 033   [   3   1   m
$ printf %s "$red" | sed -n l # POSIX
33[31m$
$ printf '%sn' "${(qqqq)red}" # zsh
$'33[31m'
$ printf '%sn' "$red" | cat -vt # some cat implementations
^[[31m
$ printf %s "$red" | uconv -x ':: [:Cc:]; ::Hex;' # ICU tools
u001B[31m
$ printf %s "$red" | uconv -x ':: [:Cc:]; ::Name;' # ICU tools
N{<control-001B>}[31m
Answered By: Stéphane Chazelas

Use od, hexdump, xxd, or similar to print binary data in human-readable form. For example:

$ tput setaf 1 | od -c
0000000 033   [   3   1   m
0000005
Answered By: lcd047
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.