Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

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"
                +1 for printf -v which is very efficient and can also change other backslash  sequences if required, otherwise could also be done in expansion "${output//'\x20'/ }"
– Nahuel Fouilleul
                Dec 14, 2018 at 17:31
$ export a="KINGSTON\x20SV100S2"
$ perl -e ' BEGIN { $x=$ENV{a}; $x=~s/\\x(\d{2})/chr(hex($1))/ge; print $x,"\n" } '
KINGSTON SV100S2
                thanks, re-assigning the variable with echo helped to solve this. HD_NAME=$(echo -e "$HD_NAME")
– waqaslam
                Dec 14, 2018 at 16:58
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.