Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove one comma using a python script

Tags:

python

vim

csv

I have csv file with a line that looks something like this:

,,,,,,,,,,

That's 10 commas. I wish to remove only the last (i.e. the 10th) comma, so that the line changes to:

,,,,,,,,,

Has anyone had any experience dealing with a case like this? I use the vim text editor also. So, any help using python script or text editing commands using vim would be appreciated.

like image 520
leba-lev Avatar asked Dec 04 '22 21:12

leba-lev


2 Answers

Removing last comma in current line in vim: :s/,$//

The same for lines n through m: :n,ms/,$//

The same for whole file: :%s/,$//

like image 144
Piotr Kalinowski Avatar answered Dec 07 '22 12:12

Piotr Kalinowski


This will do it in the simplest case, once you've updated your question with what you're looking for, I'll update the code.

commas = ",,,,,,,,,,,"
print commas.replace(","*10, ","*9)

If you want to remove the last comma on any given line you can do:

import re
commas = """,,,,,,,,,,
            ,,,,,,,,,,"""
print re.sub(r',$', '', commas, re.MULTILINE)

And if, in any file, you want to take a line that is just 10 commas and make it 9 commas:

import re
commas = ",,,,,,,,,,\n,,,,,,,,,,\n,,,,,,,,,,"
print re.sub(r'^,{10}$', ','*9, commas, re.MULTILINE)
like image 43
marr75 Avatar answered Dec 07 '22 11:12

marr75