0

I have a string that goes like this abcd'efgh\ ijkl\ mnop

I want to make the string into abcd\'efgh\ ijkl\ mnop

sed 's/\'/\\\'/g didn't work

an0nhi11
  • 59
  • 1
  • 7
  • 1
    You were on right path, you need to just escape `'`(single quote) and your substitution part will work then. Since you are on right track for substituting `'` with `\'` only thing is you need to escape `'`. There are many answers given in attached dupe link for reference the same. – RavinderSingh13 Nov 04 '21 at 10:33
  • 1
    @RavinderSingh13 Wiktor convinced me that it was not the same question but that's too much even for me. Now take it to meta if you want that deleted. Over – Jean-François Fabre Nov 04 '21 at 10:36
  • 1
    @Jean-FrançoisFabre, you could mention that reason that convinced you, so that I/we could be aware of that also. I haven't said or flagged anything to delete this etc. I believe with due respect we could request to know the reason of reopening of you it could be told, thank you. Note: if we see this link https://stackoverflow.com/a/24751341/5866580 it exactly does same thing what is given in this post's answer in terms of escaping `'`. – RavinderSingh13 Nov 04 '21 at 10:38
  • 1
    Posting these comments again here for users and OP. Also this particular answer in 2nd attached dupe link(https://stackoverflow.com/a/24751341/5866580) gives exact way `"'"` of escaping `'` in `sed` posted in this question. – RavinderSingh13 Nov 04 '21 at 10:39

1 Answers1

3

You can use

sed 's/'"'"'/\\&/g'

See the online demo:

#!/bin/bash
s="abcd'"'efgh\ ijkl\ mnop'
sed 's/'"'"'/\\&/g' <<< "$s"
# => abcd\'efgh\ ijkl\ mnop
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563