Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transpose the contents of lines and columns in a file in 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 original file might be:

THE DAY WAS LONG 
THE WAY WAS FAST

and after the transposition, it should become:

TT
HH
EE

DW
AA
YY

WW
AA
SS

LF
OA
NS
GT

Update

  • Golf rules apply to selecting correct answer.
  • Python fans should check out Charles Duffy’s answer below.
like image 635
ojblass Avatar asked Apr 01 '09 05:04

ojblass


People also ask

How do I transpose rows to columns in Linux?

Click the cell that is to be the top left cell in the result. Choose Edit - Paste Special. In the dialog, mark Paste all and Transpose. If you now click OK the columns and rows are transposed.


1 Answers

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()

Put this in newly created .vim file inside vim/plugin dir or put this to your [._]vimrc.
Execute :TransposeBuffer to transpose current buffer

like image 55
Mykola Golubyev Avatar answered Nov 12 '22 20:11

Mykola Golubyev