Remove EOL spaces of selection only if there are

只谈情不闲聊 提交于 2019-12-11 04:35:44

问题


How do I check if a selection has EOL spaces and remove them only if there are?

I need to remove the EOL spaces of a selection in order to do an other operation.
I would like to check if there are but don't know how to do this.


回答1:


You can suppress errors in the :substitute command using the e flag. So eckes' suggestion would become:

:'<,'>s/\ \+$//ge

Then any errors are ignored, and scripts are not interrupted. See :help s_flags for more information.

If you really want to check if there are trailing spaces you could try using something like

if matchstr(getline("."),'\s\+$') == ""
    " there is no trailing whitespace
else
    " there is some trailing whitespace
endif



回答2:


While the selection is active (visual mode), simply type

:s/\ \+$//g

On the command line this will become

'<,'>s/\ \+$//g

Hit Enter, mission complete.

If there are no trailing spaces, an error (E486) will be thrown but that's no problem.


Edit 1:
To be sure that you apply the substitution only where there really are occurrences of trailing white space, you could prefix the :s by :g:

:g/\ \+$/s/\ \+$//g

The trick of :g is that it applies the given command (s/\ \+$//g) only on those lines that match the given pattern.


Edit 2:
Things get even shorter, as I recently learned:

:g/\s\+$/s///g



回答3:


If you are looking to remove all white-space, the shortest command would probably be

:%s/\s*$//

% applies to entire buffer

s substitute

/\s*$ match any whitespace followed by end-of-line

// replace matches with empty



来源:https://stackoverflow.com/questions/9803579/remove-eol-spaces-of-selection-only-if-there-are

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!