How can I find/replace instances of double hyphens (--) with triple hypens (---) in vim?

3

I know there's probably a way to do that using regex, but I can't quite seem to figure out regex in vim. I tried searching: /-\{2} but it catches triple hyphens, too.

I also can't just do a traditional find and replace, since I have triple hyphens in my file. Searching for -- returns triple hyphens in addition to double hyphens.

Jonathan

Posted 2012-02-18T23:03:15.943

Reputation: 1 539

2Did you try :%s/--/---/g? It works for me. – Tomer Vromen – 2012-02-18T23:27:11.727

I should have said that my file also contains triple hyphens, so if I do that, I would get triple hyphens turning into quadruple hyphens. – Jonathan – 2012-02-19T18:54:19.127

Answers

8

How about :%s,-\@<!---\@!,---,g? That way it won't change '---' to '----'.

Dr Kitty

Posted 2012-02-18T23:03:15.943

Reputation: 504

That works, thanks! I don't understand how, but I'll go look up what commas and @ symbols mean in vim. – Jonathan – 2012-02-19T19:03:15.147

2@Jon The comma is a delimiter—whatever character immediately follows it is used to separate the search expression, the replace expression, and any options (in this case g). (Usually / is used, but it's not so nice to look at when you have lots of backslashes.) The -\@<! prevents the pattern from matching immediately after a '-', and the `-@!' keeps it from matching immediately before a '-'. – Dr Kitty – 2012-02-20T00:29:21.310

2

Your example works for me, so I suspect you have a different character in your file that only looks like a hyphen.

I would suggest placing your cursor on one in normal mode, typing yl to yank the character, then typing / followed by pressing control-r then " (double quote). If that works, you can use the same trick to create your substitute command.

Heptite

Posted 2012-02-18T23:03:15.943

Reputation: 16 267

I should have said above that my example, while it returns double hyphens, also returns triple hyphens, and so if I were to do a find/replace using that example, it would turn all my triple hyphens into quadruple hyphens, which is not what I want. But thanks very much for the yl, /, ctrl-r, " trick--I didn't know that one, and that's going to solve a lot of other problems for me. – Jonathan – 2012-02-19T19:01:35.737