2

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.

2

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.

1

Try this:

string=$'New\x20Folder'

or

string="New\x20Folder"
string="$(echo -e "$string")"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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