Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 927
asteri Avatar asked Dec 18 '12 19:12

asteri


1 Answers

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.

like image 68
Rohit Jain Avatar answered Oct 02 '22 20:10

Rohit Jain