0

I am trying to write different sed scripts for beautifying ruby code. One of the cases i am trying to solve is to replace a=>b or a=> b strings with a => b. The regex for matching this condition is [^ ]=> but it also matches 1 character before =>. So, when i try to replace it is not giving me the desired result with s/[^ ]=>/ =>/g

Any suggestions?

pguardiario
  • 53,827
  • 19
  • 119
  • 159
Pratik Khadloya
  • 12,509
  • 11
  • 81
  • 106

2 Answers2

1

You need to use a capture:

s/\([^ ]\)=>/\1 =>/g
rici
  • 234,347
  • 28
  • 237
  • 341
  • That worked in Vim thanks! But the same dosent seem to be working in sed. – Pratik Khadloya Apr 21 '13 at 03:47
  • sed -i 's/\([^ ]\)=>/\1 =>/g' app/models/campaign.rb sed: 1: "app/models/campaign.rb": command a expects \ followed by text – Pratik Khadloya Apr 21 '13 at 03:51
  • This worked. sed -i '' 's/([^ ])=>/\1 =>/g' app/models/campaign.rb – Pratik Khadloya Apr 21 '13 at 03:56
  • @PratikKhadloya: I have no idea why that would work; I would have expected you to need to use the `-r` command-line flag with GNU sed in order to avoid having to use `\(` for captures. But I'm glad you got it working. – rici Apr 21 '13 at 04:19
  • @PratikKhadloya: Yes, the `-i` flag can be used to (appear to) do edits in place. But I don't think it changes the type of regex used by `sed`. Otherwise, you'd need to use `s/\(...`, but you seem to be saying that you used `s/(...`. – rici Apr 21 '13 at 06:21
0

How about replacing both sides unconditionally?

s/ ?=> ?/ => /g
Ry-
  • 218,210
  • 55
  • 464
  • 476