LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Automatic special character escaping in Bash scripts? (https://www.linuxquestions.org/questions/linux-software-2/automatic-special-character-escaping-in-bash-scripts-194060/)

wipe 06-16-2004 03:31 AM

Automatic special character escaping in Bash scripts?
 
Hi

I would like to basically do the opposite of "echo -e" or "echo $'stuff'". That is, instead of interpreting the escaped special C-like sequences, such as \n, my Bash script would print the supplied string with everything special and non-printable in the backslash-escaped form.

It surprises me that this kind of functionality doesn't seem to be implemented as (or in) a normal utility like echo. Programs like ls seem to use such routines (--quoting-style argument). The task is probably easy with Perl, Python or some such language, but it seems a bit overkill and I'd like to do it in a shell script. If I were to make the function myself, I would have to be able to turn characters into octal sequences.

Cheers
Simon

dash9 06-05-2009 07:41 PM

Quote:

Originally Posted by wipe (Post 993394)
Hi

I would like to basically do the opposite of "echo -e" or "echo $'stuff'". That is, instead of interpreting the escaped special C-like sequences, such as \n, my Bash script would print the supplied string with everything special and non-printable in the backslash-escaped form.

It surprises me that this kind of functionality doesn't seem to be implemented as (or in) a normal utility like echo. Programs like ls seem to use such routines (--quoting-style argument). The task is probably easy with Perl, Python or some such language, but it seems a bit overkill and I'd like to do it in a shell script. If I were to make the function myself, I would have to be able to turn characters into octal sequences.

Cheers
Simon

I think printf does what you want:
Code:

$ x="a
b"

$ printf '%q\n' "$x"
$'a\nb'

$ echo $'a\nb'
a
b



All times are GMT -5. The time now is 07:06 PM.