I have looked at this question, but it does not cover my use case.
Suppose I have the variable foo
which holds the four-character literal \x60
.
I want to perform ANSI C Quoting on the contents of this variable and store it into another variable bar
.
I tried the following, but none of them achieved the desired effect.
bar=$'$foo'
echo $bar
bar=$"$foo"
echo $bar
Output:
$foo
\x61
Desired output (actual value of \x61
):
a
How might I achieve this in the general case, including non-printable characters? Note that in this case a
was used just as an example to make it easier to test whether the method worked.
The following works:
The command bar=$'\x61' has to be constructed first, then eval evaluates the newly built command.
Since bash 4.4 there is a variable expansion to do exactly that:
To set another variable use:
I just found out that I can do this. Edited based on comments.
Sample of conversion via shell. Problem, the code is octal using
\0nnn
and hexdecimal (not on all shell) using\xnn
(wheren
are [hexa]digit)with awk, you could certainly convert it directly
The best method I know is
As mentioned in the comments, this trims trailing newlines from
$foo
. To overcome this:By far the simplest solution, if you are using
bash
:Or, to save it in another variable name
bar
:From
help printf
:There are edge cases, though: