'Un/Escaping C ANSI control codes and backslashes in bash

I have a literal text string such as the following (stored in the $string variable):

\\na\x0e\\a\a

I need to read this string and return the unescaped version of it.

I tried using GNU sed (xxd is used for visual purposes):

$ sed 's/\\\\/\\/g; s/\\n/\n/g; s/\\a/\a/g; s/\\x0e/\x0e/g' <<< "${string}" | xxd
0000000: 0a61 0e07 070a           .a....

however, it does not return the output I really want:

0000000: 5c6e 610e 5c61 07        \na.\a.

Is there a working and, potentially more reliable solution to this? As the title notes, I also would like to take unescaped strings and escape them. Maybe something as simple as:

$ ansi-stream --escape --include-bslash <<< "${string}"

or:

$ ansi-stream --unescape --include-bslash <<< "${string}"

I would also like to ignore NUL bytes, as they are string terminators in my script.

Using Debian Bullseye GNU/Linux and bash 5.1.16, in case that is relevant.


A full list of characters I wish to escape/unescape are available in the below image: table of hex values to escape

It might also be useful to mention that my input will also contain Unicode characters, such as , which I want to preserve and not un/escape.



Solution 1:[1]

For unescaping:

[Bash-5.2] % help printf
printf: printf [-v var] format [arguments]

[...]

    In addition to the standard format specifications described in printf(1),
    printf interprets:

      %b        expand backslash escape sequences in the corresponding argument

[...]
[Bash-5.2] % printf '%b' '\\na\x0e\\a\a' | hexdump -C
00000000  5c 6e 61 0e 5c 61 07                              |\na.\a.|
00000007

Don't know if there is an elegant way for escaping. You can try like this if it's not too ugly for you.

[Bash-5.2] % echo hello world | xxd -i
  0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0a
[Bash-5.2] % echo hello world | xxd -i | tr -cd 'xX[:xdigit:]' | sed 's/0x/\\x/g'
\x68\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x0a

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1