Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a string like New\x20Folder. Special characters is represented by their codes. I'd like to transform the string into quoted form: "New Folder".

The only available tools are bash and bunch of standard utilities like sed.

The first form is produced by the udev environment variable ID_FS_LABEL_ENC. The needed form is consumed by the autofs config file. It expects quoted strings.

share|improve this question
up vote 2 down vote accepted

Assuming that backslashes themselves are also escaped in your strings (as \x5c, presumably), which udev seems to do, you should use Bash's printf builtin:

printf -v translated '"%b"' "$ID_FS_LABEL_ENC"

If we try that on your example string:

$ ID_FS_LABEL_ENC='New\x20Folder'
$ printf -v translated '"%b"' "$ID_FS_LABEL_ENC"
$ echo "Translated to: '$translated'"
Translated to: '"New Folder"'

we get the transformation you wanted.

printf -v assigns the result of a standard printf-style translation into a variable, and the %b format is a Bash extension performing backslash escape sequences. This is not susceptible to any funny business with names containing odd but legitimate characters and doesn't require rewriting the string.

share|improve this answer

Try this:

string=$'New\x20Folder'

or

string="New\x20Folder"
string="$(echo -e "$string")"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.