3

I have a text file I am trying to set up to import into my DB. I need to delete everything on each line after a certain position on the line. I also need to insert commas into multiple fixed positions on each line. The end goal being a csv file which I will import into my DB.

I assume there is a regex or VIM command to insert delete by position but I am very new to both and my searches have not provided a good answer.

lostinthebits
  • 661
  • 2
  • 11
  • 24
  • What are the comma positions and what is the delete position? There are a couple of ways to do it, one of which is to record a simple macro. – Michael Berkowski Aug 08 '13 at 18:46
  • The delete position would be everything after position 115 on the line. The comma positions would be 10, 20, 30, 48, 52, 60, 70. But I'm assuming the solution would be able to swap in any position? – lostinthebits Aug 08 '13 at 18:48
  • @MichaelBerkowski - I did see your post on the macro just before you deleted it and it did work. Am looking at the regex now but thank you for your suggestion! – lostinthebits Aug 08 '13 at 19:12
  • Ingo's solution is *waaaaaay* better than my complicated macro, which is why I removed it. – Michael Berkowski Aug 08 '13 at 19:15

1 Answers1

10

Vim has a special regular expression atom \%23c that matches in column 23. You can also match before and after that, see :help /\%c. With that, you can achieve your goals through a :substitute: Delete all characters after position 115:

:%s/\%>115c.*//

Insert a comma at positions 10, 20, 30:

:%s/\%10c\|\%20c\|\%30c/,/g

This works because the match itself is zero width, i.e. it doesn't consume the character at that position. To do that, you need to append something like ..

Note that the \%c atom works on characters (byte counts, to be exact). To properly deal with multibyte and double-width characters, Tabs, etc., you probably better base this on the screen width: \%v is the atom.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
  • Hi Ingo Karkat, can you help me with this question? https://stackoverflow.com/questions/70412647/how-to-insert-character-based-on-position-vim – jian Dec 19 '21 at 15:15