Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to rearrange columns in a tab delimited text file in vim?

Tags:

vim

I already know how to do it with

:%s/\(\S\+\)^I\(\S\+\)/\2^I\1/

but I feel like I'm typing way to much stuff. Is there a cleaner, quicker way to do it?

like image 409
mmarchin Avatar asked Jun 25 '10 15:06

mmarchin


2 Answers

If the columns are lined up, you can use visual block mode by hitting Ctrl+V, then cut and paste. If the columns are not lined up, increase the tab width first so that it's longer than the content of the columns in question.

like image 85
Brian Avatar answered Oct 13 '22 21:10

Brian


Best way to do it in VIM is - not to do it with VIM and (re)use existing tools for the job. *NIX specific solution:

:%!awk -F \\t '{print $2 FS $1}'

Would pipe the content of the tab-delimited file to awk and it will print first two columns swapped, separated by field separator (FS). awk can be also found for Windows.

P.S. Initially I wanted to write the same with cut but for whatever reason on my system the cut -f 2,1 (-d is not needed as TAB is the default delimiter) printed the fields in the same order, not swapped :|

like image 36
Dummy00001 Avatar answered Oct 13 '22 20:10

Dummy00001