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.
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:
y/'/"/ in sed for transliterating between two sets of characters efficiently.
– Kusalananda
Oct 23 '19 at 12:23
'\''. (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
With bash, you cannot embed a single quote in a single quoted string, no matter how you try to escape it.
Some options:
"s/'/\"/g"'s/'"'"'/"/g' or 's/'\''/"/g'$'s/\'/"/g's/\'/\"/gFor 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
sed 's/\x27/"/g'where\x27is the hex sequence for a single quote. – Rakesh Sharma Oct 24 '19 at 08:42s/'/"/gThen invoke sed as:sed -f cmds– Rakesh Sharma Oct 24 '19 at 08:51