0

I tried to replace end of lines in a file with single quote + comma.

Content of test.txt file:

aaa
bbb
ccc

Expected result:

aaa',
bbb',
ccc',

I managed to replace the end of lines with comma like this: sed 's#$#,#g' test.txt

but i always fail when trying to convert to single quote + comma. I tried: sed 's#$#',#g' test.txt but the command still awaiting input.

I tried various combination with quotes and double quotes but still fail.

I'd really appreciate your help. thanks.

fauzimh
  • 594
  • 4
  • 16

3 Answers3

1

Single quotes can't be nested. You have to end the single quotes, add an escaped or quoted single quote, than open a new quoted string.

sed 's/$/'\'',/'
sed 's/$/'"'"',/'

You can also switch the quotes and use double quotes for the whole expression:

sed "s/$/',/"

In fact, the substitution needs no quoting in this case, so you can just use

sed s/$/\',/
choroba
  • 231,213
  • 25
  • 204
  • 289
  • Or switch quotes: `sed "s/$/',/"`. (The dollar sign in general needs to be quoted to prevent parameter expansion in double quotes, but here it's fine because `$/` is not a special parameter expansion.) – chepner Mar 30 '23 at 12:08
  • thanks @choroba, i learn something new! you have been very helpful – fauzimh Mar 30 '23 at 14:06
1

This isn't really a question about sed so much as it is a question about quoting in the shell. If you want a single quote in a string, the 2 typical ways to get it are to enclose it in double quotes or to escape it with \. To pass that string as an argument to sed you could do any of:

sed "s/\$/',/"

or

sed s/$/\',/

or

sed 's/$/'"',/"  # escape the $ with single quotes and the ' with double quotes
William Pursell
  • 204,365
  • 48
  • 270
  • 300
1

1)

You should be aware of what character(s) are you using in script of sed command.

Simply, if you are using special characters (in this case: the "single quote" character) as a character of your script (not character of syntax), technically you can escape it.

In sed's script and a lot of programming languages you can use "\" as an escape character.

2)

If your script needs to be (1)quoted (with quoting characters) and you're using a quoting character (2)in your script, then the (2) must be different from (1).

Result:

The code should be like this example:

[sinuxnet@hostname]$ sed -r "s/$/\',/g"

More to read:

  1. Escape character - Wikipedia
  2. A Guide to Unix Shell Quoting
sinuxnet
  • 26
  • 4