0
votes

I'm running a shell command which returns raw string that is a combination of ASCII and Hex chars. The character it embeds is space-chars in hex. Below is the output:

KINGSTON\x20SV100S2
ST380011A\x20\x20\x20\x20\x20\x20\x20
Maxtor\x206L300S0\x20\x20

How can I replace all the \x20 into single ASCII space character?

Expected output:

KINGSTON SV100S2
ST380011A
Maxtor 6L300S0

P.S the string is stored in a bash variable, hence I would prefer a solution that doesn't input file.

4

4 Answers

4
votes

To only replace \x20 and nothing else use sed:

sed 's/\\x20/ /g' <<< "$output"

or

yourCommand | sed 's/\\x20/ /g'

To replace all escape sequences use echo -n (as kvantour already pointed out) or even better, the more portable printf %b which can also assign directly to variables without using $():

printf -v output %b "$output"
2
votes

You can try Perl also

$ perl -e ' BEGIN { print "KINGSTON\x20SV100S2","\n" } '
KINGSTON SV100S2
$

or

you can export it to environment

$ export a="KINGSTON\x20SV100S2"
$ perl -e ' BEGIN { $x=$ENV{a}; $x=~s/\\x(\d{2})/chr(hex($1))/ge; print $x,"\n" } '
KINGSTON SV100S2
$
1
votes

A quick way would be to use echo -e

$ echo -e "KINGSTON\x20SV100S2"
KINGSTON SV100S2

-e enable interpretation of backslash escapes

Or just use printf

$ printf "KINGSTON\x20SV100S2"
KINGSTON SV100S2
1
votes

printf is more portable than echo -e. You need to use %b format. As per help printf:

%b expand backslash escape sequences in the corresponding argument

Define a utility function:

expbs() { printf '%b\n' "$@"; }

Then use it as:

expbs 'KINGSTON\x20SV100S2'
KINGSTON SV100S2

expbs 'ST380011A\x20\x20\x20\x20\x20\x20\x20'
ST380011A

expbs 'Maxtor\x206L300S0\x20\x20'
Maxtor 6L300S0