如何在 Vim 中修剪文件末尾的空行? [英] How can I trim blank lines at the end of file in Vim?

查看:25
本文介绍了如何在 Vim 中修剪文件末尾的空行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我不小心在我正在编辑的文件末尾留下空行.
如何在 Vim 中保存时修剪它们?

Sometimes I accidentally leave blank lines at the end of the file I am editing.
How can I trim them on saving in Vim?

谢谢大家,所有解决方案似乎都有效.
不幸的是,他们都重置了当前光标位置,所以我写了以下函数.

Thanks guys, all solutions seem to work.
Unfortunately, they all reset current cursor position, so I wrote the following function.

function TrimEndLines()
    let save_cursor = getpos(".")
    silent! %s#\($\n\s*\)\+\%$##
    call setpos('.', save_cursor)
endfunction

autocmd BufWritePre *.py call TrimEndLines()

推荐答案

这个替代命令应该这样做:

This substitute command should do it:

:%s#\($\n\s*\)\+\%$##

请注意,这会删除所有仅包含空格的尾随行.要仅删除真正的空"行,请从上述命令中删除 \s*.

Note that this removes all trailing lines that contain only whitespace. To remove only truly "empty" lines, remove the \s* from the above command.

编辑

说明:

  • \( ..... 开始比赛组
  • $\n ... 匹配新行(行尾字符后跟回车符).
  • \s* ... 在这个新行上允许任意数量的空格
  • \) ..... 结束比赛组
  • \+ ..... 允许该组出现任意次数(一次或多次).
  • \%$ ... 匹配文件末尾
  • \( ..... Start a match group
  • $\n ... Match a new line (end-of-line character followed by a carriage return).
  • \s* ... Allow any amount of whitespace on this new line
  • \) ..... End the match group
  • \+ ..... Allow any number of occurrences of this group (one or more).
  • \%$ ... Match the end of the file

因此,正则表达式匹配任意数量的仅包含空格的相邻行,仅在文件末尾终止.然后替换命令将匹配替换为空字符串.

Thus the regex matches any number of adjacent lines containing only whitespace, terminated only by the end of the file. The substitute command then replaces the match with a null string.

这篇关于如何在 Vim 中修剪文件末尾的空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆