Segfault
Segfault

Reputation: 65

Vim how to move csv column

Suppose a classic csv like this :

1,2,3,4,5,6,7
1,2,3,4,5,6,7
1,2,3,4,5,6,7

I was trying to move the 6th column of each line to the beginning of the line using a simple and elegant one liner.

Is there a way to achieve this using something like :

g/,/norm 5n<?>d0P

I don't know what to put in place of <?> to select the word right after the 5th comma

Upvotes: 2

Views: 552

Answers (1)

SergioAraujo
SergioAraujo

Reputation: 11820

A little modification on the global command

:g/./exec 'normal 5f,lvld0P'

:g  .............. globally
/./  ............. on each line that has something
exec ............. execute the following normal command
5f, .............. jumpt to the fifht ,
l ................ move to the number
vl ............... select the number and its coma
d ................ cut to the unamed register
0 ................ jump to the beginning of line
P ................ past the content of default register (before)

Update

Instead of simply selecting the number and the next coma we select until the next coma. (This is a more generic solution), avoiding issues with columns who possibly have double digit or more numbers.

g/./exec 'normal 5f,ldf,0P'

Using gnu awk

awk -i inplace -F, -v OFS="," '{print 6,1,2,3,4,5,7}' target-file

-i inplace  ............. no need to use temp file
-F ...................... field separator
-v OFS .................. output field separator

Calling awk from vim

:%! awk -F, -v OFS="," '{print 6,1,2,3,4,5,7}'

% ............... current file
! ............... filter trhough external command

Upvotes: 2

Related Questions