Mark
Mark

Reputation: 3

Use sed to replace all ' with \' and all " with \"

I want to use sed to replace all ' with \' and all " with \". Example input:

"a" 'b'

Output:

\"a\" \'b\'

Upvotes: 0

Views: 217

Answers (2)

carlo
carlo

Reputation: 11

While using sed is the portable solution, all this can be done using Bash's builtin string manipulation functions as well.

(
#set -xv
#str=$'"a" \'b\''
str='"a" '"'b'"  # concatenate 'str1'"str2"
str="${str//\"/\\\"}"
str="${str//\'/\'}"
echo "$str"
)

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 224854

There's no ? character in your post, but I'll assume your question is "How do I do such a replacement?". I just made a quick test file with your input, and this command line seems to work:

sed -e 's#"#\\"#g' -e "s#'#\\\'#g"

Example:

$ cat input 
"a" 'b'
$ sed -e 's#"#\\"#g' -e "s#'#\\\'#g" input 
\"a\" \'b\'

Upvotes: 1

Related Questions