5

I need to replace all single quotes ' contained in /tmp/myfile with " (double quotes)

I'm using this

sed -i 's/'/\"/g' /tmp/myfile

and other combinations but I cannot find a way which works.

Any help please.

gr68
  • 334

3 Answers3

15

To replace single quotes (') it's easiest to put the sed command within double quotes and escape the double quote in the replacement:

$ cat quotes.txt 
I'm Alice
$ sed -e "s/'/\"/g"  quotes.txt 
I"m Alice

Note that the single quote is not special within double quotes, so it must not be escaped.

If, instead one wants to replace backticks (`), as the question originally mentioned, they can be used as-is within single quotes:

$ cat ticks.txt
`this is in backticks`
$ sed -e 's/`/"/g'  ticks.txt
"this is in backticks"

Within double quotes, you'd need to escape the backtick with a backslash, since otherwise it starts an old-form command substitution.

See also:

ilkkachu
  • 138,973
  • 4
    Also, y/'/"/ in sed for transliterating between two sets of characters efficiently. – Kusalananda Oct 23 '19 at 12:23
  • 1
    Thank you , yes I wanted say "single quotes" to "double quotes" – gr68 Oct 23 '19 at 12:31
  • 2
    If you still want the absolute robustness of single-quotes (which are different and safer and simpler than double-quotes in all Bourne-family-tree shells), the correct way to escape a single quote inside single quotes is '\''. (End single-quoting, backslash-escape a single single-quote, resume single-quoting.) Memorize it. Burn it into your mind. It will make your life better, and everyone else's life better, and the world as a whole better, etc. – mtraceur Oct 24 '19 at 00:16
8

With bash, you cannot embed a single quote in a single quoted string, no matter how you try to escape it.

Some options:

  1. use double quotes as ilkkachu suggests: "s/'/\"/g"
  2. concatenate string segments: 's/'"'"'/"/g' or 's/'\''/"/g'
  3. use an ANSI-C quotes: $'s/\'/"/g'
  4. don't quote the whole thing, escape the chars that need escaping: s/\'/\"/g
mtraceur
  • 1,166
  • 9
  • 14
glenn jackman
  • 85,964
7

For a single character change, tr might be quickest:

tr \' \" <infile >outfile

Note that both quotes need escaping in the shell environment. Or for replacing in the same file, use sponge (from moreutils package)

tr \' \" <infile | sponge infile
FelixJN
  • 13,566