17

I have a file "test.txt" that contain the following

+foo+
+bar+

What I want to do is to replace them into:

'foo'
'bar'

But why this code doesn't work?

sed  's/\+/\'/' test.txt

What's the right way to do it?

neversaint
  • 50,277
  • 118
  • 274
  • 437

4 Answers4

25

Use " instead. And add g flag to replace all.

sed  "s/\+/\'/g" test.txt
falsetru
  • 314,667
  • 49
  • 610
  • 551
  • sed "s/\$/\'/g" ut.txt - this is adding ' at the end instead replacing the $ character. am i missing something? – Anu Jul 04 '17 at 10:55
  • As [anubhava](https://stackoverflow.com/a/18119525) mentions, `+` is not a metacharacter without the `-r` option, thus `sed "s/+/'/g" test.txt` should do the trick. – thymaro Apr 19 '21 at 06:41
5

This might work for yoyu (GNU sed):

sed 'y/+/'\''/' file
potong
  • 47,186
  • 6
  • 43
  • 72
3

+ is not a special character without -r switch in sed. You can run the substitute command without any escaping:

echo '+foo+' | sed "s/+/'/g"

# output: 'foo'

If you want to save changed file then use:

sed -i.bak "s/+/'/g" test.txt
anubhava
  • 664,788
  • 59
  • 469
  • 547
3

You can also replace all instances of + with ' in the file by using tr:

tr '+' "'" < inputfile
devnull
  • 103,635
  • 29
  • 207
  • 208