I have a string in a shell/bash script. I want to print the string with all its "special characters" (eg. newlines, tabs, etc.) printed as literal escape sequences (eg. a newline is printed as \n
, a tab is printed as \t
, and so on).
(Not sure if I'm using the correct terminology; the example should hopefully clarify things.)
The desired output of...
a="foo\t\tbar"
b="foo bar"
print_escape_seq "$a"
print_escape_seq "$b"
...is:
foo\t\tbar
foo\t\tbar
$a
and $b
are strings that were read in from a text file.foo
and bar
in the $b
variable.This is what I've tried:
#!/bin/sh
print_escape_seq() {
str=$(printf "%q\n" $1)
str=${str/\/\//\/}
echo $str
}
a="foo\t\tbar"
b="foo bar"
print_escape_seq "$a"
print_escape_seq "$b"
The output is:
foo\t\tbar
foo bar
So, it doesn't work for $b
.
Is there an entirely straightforward way to accomplish this that I've missed completely?
We have many escape characters in Python like , , , etc., What if we want to print a string which contains these escape characters? We have to print the string using repr () inbuilt function.
In fact, you can type any character, both printable and non-printable, just by using their hexadecimal Unicode sequences as escape sequences. To use this format, you use \x as your escape character followed by the appropriate Unicode. For example, the escape sequence \x56 is the letter V. Here is an example that uses a few of these codes.
HTML uses two different sets of escape sequences. The first, known as HTML character entities, is used directly in HTML code to represent special characters. The other set is used by web browsers to allow special and non-English characters in web addresses.
All escape sequences begin with an escape character that signals the start of the sequence. In the past, this character was a dedicated character sent by the Esc key, but today, most programming languages use the backslash (\) instead.
You will need to create a search and replace pattern for each binary value you wish to replace. Something like this:
#!/bin/bash
esc() {
# space char after //
v=${1// /\\s}
# tab character after //
v=${v// /\\t}
echo $v
}
esc "hello world"
esc "hello world"
This outputs
hello\sworld
hello\tworld
Bash has a string quoting operation ${var@Q}
Here is some example code
bash_encode () {
esc=${1@Q}
echo "${esc:2:-1}"
}
testval=$(printf "hello\t\tworld")
set | grep "^testval="
echo "The encoded value of testval is" $(bash_encode "$testval")
Here is the output
testval=$'hello\t\tworld'
The encoded value of testval is hello\t\tworld
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With