Reputation: 3
I want to print a text example
'(]\{&}$"\n
the escaped version I have is this:
"'(]\\{&}$\"\\n"
I tried the following:
cat $CLIPBOARD_HISTORY_FILE | sed "$2!d" | sed 's/^.\(.*\).$/\1/'
cat $CLIPBOARD_HISTORY_FILE | sed "$2!d" | sed 's/^.\(.*\).$/\1/' | eval 'stdin=$(cat); echo "$stdin"'
VAR1=$(cat $CLIPBOARD_HISTORY_FILE | sed "$2!d" | sed 's/^.\(.*\).$/\1/')
VAR2="'(]\\{&}\$\"\\n"
VAR3=$VAR1
echo "1 '(]\\{&}\$\"\\n"
echo "2 $VAR1"
echo "3 $VAR2"
echo "4 $VAR3"
echo -e "5 $VAR1"
echo -e "6 $VAR2"
echo -e "7 $VAR3"
$
'(]\\{&}$\"\\n
'(]\\{&}$\"\\n
1 '(]\{&}$"\n
2 '(]\\{&}$\"\\n
3 '(]\{&}$"\n
4 '(]\\{&}$\"\\n
5 '(]\{&}$\"\n
6 '(]\{&}$"
7 '(]\{&}$\"\n
echoing the text directly works, but not if it comes from a command.... what am I not seeing or understanding? Thanks for the help!
Upvotes: 0
Views: 108
Reputation: 753870
In general, it's best to enclose material in single quotes rather than double quotes; then you only have to worry about single quotes. Thus:
$ x="'"'(]\{&}$"\n'
$ printf "%s\n" "$x"
'(]\{&}$"\n
$ printf "%s\n" "$x" | sed -e "s/'/'\\\\''/g" -e "s/^/'/" -e "s/$/'/"
''\''(]\{&}$"\n'
$
The use of printf
is important; it doesn't futz with its data, unlike echo
.
The '\''
sequence is crucial; it stops the current single quoted string, outputs a single quote and then restarts the single quoted string. That output is 'sub-optimal'; the initial ''
could be left out (and similarly the final ''
could be left out if the data ends with a single quote):
$ printf "%s\n" "$x" | sed -e "s/'/'\\\\''/g" -e "s/^/'/" -e "s/$/'/" -e "s/^''//" -e "s/''$//"
\''(]\{&}$"\n'
$
If you really must have double quotes around the data, rather than single quotes, then you have to escape more ($`\"
need protection), but the concept is similar.
Upvotes: 1