Question

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, ^.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top