3

Suppose a classic csv like this (each number represents an alphanumeric sequence) :

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

2
2

You can try it with :normal! command alone:

:%normal! 05f,dF,0Pm`0x``P

Which executes normal commands for all lines (%) one by one:

  • 0 to go to beginning of the line
  • 5f, to go to 5th comma
  • dF, to cut back till comma
  • 0 to the beginning
  • P to Paste before current char
  • m` to mark end of pasted text
  • 0 to go to beginning of the line where now there is a comma
  • x to cut a comma
  • `` to go to the end of the pasted text we marked earlier
  • P to paste a comma

Note, it wouldn't work for a well formed csv with "fields that have, commas".

There are probably better ways to do it too :)

PS, you can replicate normal command just typing it on the csv line 05f,dF,0Pm`0x``P

PPS, tested with:

1,2,3,4,5sdf skljsf,6,7
1,2,3,4,5 sdkj lskdj ,6,7
1,2,3,4,5 aksldjfl sjdf ,6,7

result:

5sdf skljsf,1,2,3,4,6,7
5 sdkj lskdj ,1,2,3,4,6,7
5 aksldjfl sjdf ,1,2,3,4,6,7
3
  • Thank you ! i didn't know about the "normal!" syntax nor the mark command, it makes total sens, this is awesome – Segfault Nov 5 '20 at 13:38
  • Another way you can apply this to multiple lines is to record the command in a macro that ends with j or j0 and then execute the macro N times. The :% in Maxim Kim's answer applies the normal command to all lines, but in some cases you may not want all lines. – nullromo Nov 5 '20 at 18:53
  • 1
    @nullromo, if you don't need all lines, visually select whatever you want and do the same normal command. Or do :g/pattern/normal .... But yes, macro is another option. – Maxim Kim Nov 5 '20 at 20:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.