In VIM, why don't you have to add back '$' in a search and replace?
Asked Answered
H

1

5

I've been learning how to do more complex search and replace functions in VIM, and I ran across a use case like this:

:%s/$/|/g

This supposedly finds the end of every line and replaces it with a vertical pipe. When I was first learning this, though, I assumed you would have to add the end-of-line character in the replacement string to get the expected results. i.e.,

:%s/$/|$/g

Why does it work without it and still preserve the line break? Shouldn't it be replacing the line's terminating character with your string and removing it in the process?

The same thing could be asked with the beginning-of-line character, ^.

Heedless answered 18/12, 2012 at 19:32 Comment(1)
If you want to match newlines explicitely (to remove them, for example, or for quick multiline substitution), use \n.Talion
M
17

Anchor $ does not include the newline character. In fact it is a zero-width token. It matches the empty character just before the first newline in your string. And hence the result.

Similarly, ^ matches an empty character before the first character in your string.

See http://www.regular-expressions.info/anchors.html for more details.

Mendacity answered 18/12, 2012 at 19:34 Comment(1)
See also :help /zero-width.Dissonant

© 2022 - 2024 — McMap. All rights reserved.