0

Say I have the following (where <space> indicates an actual whitespace character)

Line 1
Line 2<space>
Line 3
Line 4<space>
Line 5

and I wanted it to be

Line 1/
Line 2/
Line 3/
Line 4/
Line 5/

I initially thought that maybe s/\s*$/\//g would work but then I ended up with the following as the solution

Line 1/
Line 2//
Line 3/
Line 4//
Line 5/

I can't think of a way to include the case where there is a whitespace character at the end that I want replaced.

Nick
  • 138,499
  • 22
  • 57
  • 95
Kalcifer
  • 1,211
  • 12
  • 18

1 Answers1

1

\s*$ can match a string ending in a space twice; once to capture the actual space character, and again to match the end of string (see for example this Q&A). This is why you are getting two replacements on the strings ending in space. To avoid this problem, use a positive lookbehind for a non-space character; that prevents the end of string that is preceded by a space being matched again. In normal regex you would match with:

(?<=\S)\s*$

and replace with a /. Demo on regex101.

In vim you can use the \zs marker to define the start of the match e.g.

:%s/\S\zs\s*$/\//
Nick
  • 138,499
  • 22
  • 57
  • 95