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.

  • In case you have access to GNU sed, you could just do: sed 's/\x27/"/g' where \x27 is the hex sequence for a single quote. – Rakesh Sharma Oct 24 at 8:42
  • without GNU sed, create a file(say cmds) with this line: s/'/"/g Then invoke sed as: sed -f cmds – Rakesh Sharma Oct 24 at 8:51

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:

  • 4
    Also, y/'/"/ in sed for transliterating between two sets of characters efficiently. – Kusalananda Oct 23 at 12:23
  • 1
    Thank you , yes I wanted say "single quotes" to "double quotes" – gr68 Oct 23 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 at 0:16

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.