Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM: insert or delete data based on position

Tags:

regex

vim

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.

like image 275
lostinthebits Avatar asked May 07 '26 04:05

lostinthebits


1 Answers

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.

like image 109
Ingo Karkat Avatar answered May 08 '26 18:05

Ingo Karkat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!