tags:

views:

97

answers:

2

I happened across this page full of super useful and rather cryptic vim tips at http://rayninfo.co.uk/vimtips.html. I've tried a few of these and I understand what is happening enough to be able to parse it correctly in my head so that I can possibly recreate it later. One I'm having a hard time getting my head wrapped around though are the following two commands to remove all spaces from the end of every line

:%s=  *$==                  : delete end of line blanks
:%s= \+$==                  : Same thing

I'm interpreting %s as string replacement on every line in the file, but after that I am getting lost in what looks like some gnarly variation of :s and regex. I'm used to seeing and using :s/regex/replacement. But the above is super confusing.

What do those above commands mean in english, step by step?

+12  A: 

The regex delimiters don't have to be slashes, they can be other characters as well. This is handy if your search or replacement strings contain slashes. In this case I don't know why they use equal signs instead of slashes, but you can pretend that the equals are slashes:

:%s/  *$//     
:%s/ \+$//     

Does that make sense? The first one searches for a space followed by zero or more spaces, and the second one searches for one or more spaces. Each one is anchored at the end of the line with $. And then the replacement string is empty, so the spaces are deleted.

I understand your confusion, actually. If you look at :help :s you have to scroll down a few pages before you find this note:

*E146*

Instead of the '/' which surrounds the pattern and replacement string, you can use any other character, but not an alphanumeric character, '\', '"' or '|'. This is useful if you want to include a '/' in the search pattern or replacement string. Example:

:s+/+//+
John Kugelman
Thanks! That explains it and is super helpful. I had absolutely no clue you could use something besides / to delimit your regex replacement.
whaley
+3  A: 

I do not know vim syntax, but it looks to me like these are sed-style substitution operators. In sed, the / (in s/REGEX/REPLACEMENT/) can be uniformly replaced with any other single character. Here it appears to be =. So if you mentally replace = with /, you'll get

:%s/  *$//
:%s/ \+$//

which should make more sense to you.

David Zaslavsky
If it were possible to accept both answers, I would. thanks!
whaley