如何在 Vim 中转置文件中行和列的内容? [英] How to transpose the contents of lines and columns in a file in Vim?
问题描述
我知道我可以使用 Awk,但我在 Windows 机器上,并且我正在为可能没有 Awk 的其他人制作一个函数.我也知道我可以编写一个 C 程序,但我不希望我正在制作的一个小 Vim 实用程序需要编译和维护.
I know I can use Awk, but I am on a Windows box, and I am making a function for others that may not have Awk. I also know I can write a C program, but I would love not to have something that requires compilation and maintenance for a little Vim utility I am making.
原始文件可能是:
THE DAY WAS LONG
THE WAY WAS FAST
转位后应该变成:
TT
HH
EE
DW
AA
YY
WW
AA
SS
LF
OA
NS
GT
更新
- 高尔夫规则适用于选择正确答案.
- Python 粉丝应该查看Charles Duffy 在下面的回答.
推荐答案
这是一个 Vim 语言的命令.所以你不必编译带有 +python 支持的 Vim.
Here is a command in Vim language. So you don't have to compile Vim with +python support.
function! s:transpose()
let maxcol = 0
let lines = getline(1, line('$'))
for line in lines
let len = len(line)
if len > maxcol
let maxcol = len
endif
endfor
let newlines = []
for col in range(0, maxcol - 1)
let newline = ''
for line in lines
let line_with_extra_spaces = printf('%-'.maxcol.'s', line)
let newline .= line_with_extra_spaces[col]
endfor
call add(newlines, newline)
endfor
1,$"_d
call setline(1, newlines)
endfunction
command! TransposeBuffer call s:transpose()
把这个放在 vim/plugin 目录中新创建的 .vim 文件中,或者把它放到你的 [._]vimrc 中.
执行:TransposeBuffer
转置当前缓冲区
Put this in newly created .vim file inside vim/plugin dir or put this to your [._]vimrc.
Execute :TransposeBuffer
to transpose current buffer
这篇关于如何在 Vim 中转置文件中行和列的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!