0

I want to change all lines in a file with zero or one space at the end to end with exactly two spaces (to force line breaks when the file is parsed with markdown).

I've done it in Sublime Text with the following find and replace regexes:

Find:    (\S)[ ]?\n
Replace: \1  \n

But out of interest, I wanted to try and do the same substitution in vim.

I tried the above but it found no matches. So I tried

:%s/\(\S\)[ ]\?\n/\1  \n/g

and it places weird characters all through the file.

On its own, /\(\S\)[ ]\?\n finds all the correct line endings.

Jim Cullen
  • 472
  • 1
  • 6
  • 15
  • Not sure if vim uses `$1` instead of `\1`. Did you try with `$1`? – Federico Piazza Oct 25 '16 at 17:33
  • See http://stackoverflow.com/a/12388814/3832970 answer, `\n` in the replacement is a null char. Use `\r` instead. – Wiktor Stribiżew Oct 25 '16 at 17:33
  • @WiktorStribiżew yes that seems to have done it. But just for clarification, it's actually still *inserting* a \n 0x0A character right? Not the \r 0x0D character? – Jim Cullen Oct 25 '16 at 17:48
  • @JimCullen You can avoid the newline issue entirely by using `\ze` to mark the end of your match. `:%s/\(\S\)[ ]\?\ze\n/\1 /g` – Randy Morris Oct 25 '16 at 18:09
  • @RandyMorris I don't think that would work. Wouldn't `:%s/\(\S\)[ ]\?\ze/\1 /g` (assuming that is what you mean — as far as I can tell, the fact that yours has a \n in it means it never finds anything) add two spaces between *every* character? – Jim Cullen Oct 25 '16 at 19:06
  • Try it with the newline. The '\ze' tells vim to require the rest of the pattern to match but do not replace anything beyond that point in the replace. – Randy Morris Oct 25 '16 at 21:29
  • Yeah, that works too. Thanks! – Jim Cullen Oct 26 '16 at 06:32
  • 1
    For what it's worth, the standard way to do it: `:%s/\v\S\zs\s?$/ /`. Or, if you also want to do it on empty lines: `:%s/\v(^|\S)\zs\s?$/ /`. – Sato Katsura Oct 26 '16 at 06:46
  • In fact `:%s/\(\w\)\s$\|\(\w\)$/\1\2 ` must be used to match only the two desired cases. – Alan Gómez Jul 10 '23 at 20:58

0 Answers0