开发者

How to read this command to remove all blanks at the end of a line

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 pars开发者_高级运维e 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?


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+/+//+


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜