trying to substitute single apostrophes to doubles. But cant get it right.
sed 's/'/"/'
In Bourne-like shells, single-quotes can't be escaped inside single quotes, so '\''
is the standard way of "embedding" a single-quote inside a single-quoted string in a shell command-line or script. It doesn't actually embed a single quote, but it achieves the desired end result.
'\''
= '
(end quote) \'
(escaped quote) and '
(start quote).
In other words, instead of:
sed 's/'/"/g'
Use:
sed 's/'\''/"/g'
Alternatively, double-quotes CAN be backslash-escaped inside double-quotes, so you could use:
sed "s/'/\"/g"
Be careful with this form - you have to escape shell meta-characters you want to be treated as string literals inside double quotes. e.g. sed 's/foo/$bar/'
replaces foo with the string literal $bar
, while sed "s/foo/$bar/"
replaces foo with the value of the current shell's $bar
variable (or with nothing if it isn't defined. Note: some values of variable $bar
can break the sed command - e.g. if $bar
contains an un-escaped delimiter like bar='a/b'
, that would cause the sed command to be s/foo/a/b/
, a syntax error)
Yet another, probably the best, alternative is to use $''
to quote your string. This style of quoting does allow single-quotes to be escaped. This changes the way that the shell interprets the quoted string, so may have other side effects if the string contains other escaped characters or character sequences (e.g. \xHH
- "HH" will be interpreted as the hexadecimal representation of an 8-bit character inside $''
, but it would be interpreted as just plain text "xHH" if it was unquoted or inside double-quotes).
sed $'s/\'/"/g'
NOTE: $''
works in bash, ksh, zsh and maybe others. It doesn't work in dash
.
With tr
(if you want to do it globally in the whole file):
tr "'" '"' <infile >outfile
Doing
sed 's/'/"/'
You basically have sed 's/'
followed by /"/'
, which is a slash and an unclosed double quoted string.
With
sed s/\'/\"/
you have no such problem.
If it feels better to quote the sed
expression (it's not needed in this case), do
sed 's/'"'"'/"/'
This is sed 's/'
followed by "'"
(a double quoted single quote), followed by '/"/'
.
Also note that if you want to emulate tr
in sed
, i.e. if you want to do single character transliterations, then using y///
is much more efficient than using s///g
(note the /g
there):
sed y/\'/\"/
echo "don't forget that" | sed 's/\x27/\"/'
'
insed 's/'\''/"/g
? – Seub May 24 '23 at 17:08