是否有一个命令可以确定 vim 中最长行的长度?并在文件开头附加该长度?
Is there a command to determine length of a longest line in vim? And to append that length at the beginning of the file?
推荐答案Gnu 的 wc 命令有一个 -L --max-line-length 选项,用于打印文件的最大行长度.请参阅 gnu man wc.freebsd wc也有-L,但没有--max-line-length,见freebsd man wc.
Gnu's wc command has a -L --max-line-length option which prints out the max line length of the file. See the gnu man wc. The freebsd wc also has -L, but not --max-line-length, see freebsd man wc.
如何在 vim 中使用这些?命令:
How to use these from vim? The command:
:%!wc -L会通过 wc -L 过滤打开的文件,使文件内容为最大行长.
Will filter the open file through wc -L and make the file's contents the maximum line length.
要保留文件内容并将最大行长度放在第一行,请执行以下操作:
To retain the file contents and put the maximum line length on the first line do:
:%yank :%!wc -L :put不使用 wc,查找最长行的长度 - awk bash 描述了如何使用 awk 来查找最长行的长度.
Instead of using wc, Find length of longest line - awk bash describes how to use awk to find the length of the longest line.
好的,现在是纯 Vim 解决方案.我对脚本有些陌生,但这里有.以下内容基于 textfilter 中的 FilterLongestLineLength 函数.
Ok, now for a pure Vim solution. I'm somewhat new to scripting, but here goes. What follows is based on the FilterLongestLineLength function from textfilter.
function! PrependLongestLineLength ( ) let maxlength = 0 let linenumber = 1 while linenumber <= line("$") exe ":".linenumber let linelength = virtcol("$") if maxlength < linelength let maxlength = linelength endif let linenumber = linenumber+1 endwhile exe ':0' exe 'normal O' exe 'normal 0C'.maxlength endfunction command PrependLongestLineLength call PrependLongestLineLength()将此代码放入 .vim 文件(或您的 .vimrc)并 :source 文件.然后使用新命令:
Put this code in a .vim file (or your .vimrc) and :source the file. Then use the new command:
:PrependLongestLineLength谢谢,解决这个问题很有趣.
Thanks, figuring this out was fun.