Page 1 of 1

Replacement expresion - Increment a found number

Posted: Mon Mar 15, 2004 5:14 pm
by jasonbb
I have a database that I need to reformat and incrament one of the fields by 1. the data looks like:

4,22,208,,1,2/6/2004 8:53:22,6,,,,0
7,23,165,,1,2/6/2004 8:53:22,5,,,,0
23,1,209,,1,2/6/2004 8:53:22,5,,,,0

It is the 3rd field that I need to increment so the above would change to:

4,22,209,,1,2/6/2004 8:53:22,6,,,,0
7,23,166,,1,2/6/2004 8:53:22,5,,,,0
23,1,210,,1,2/6/2004 8:53:22,5,,,,0

Is it possible to do this with a regular expresion?

Thank You,
Jason

Posted: Mon Mar 15, 2004 6:33 pm
by MudGuard
No, regular expressions are not able to do arithmetics.

Posted: Mon Mar 15, 2004 6:52 pm
by talleyrand
Install Python and you're good to go.

Copy this code and paste into Textpad.
Save it to something like C:\jasonbb.py
Update the fileName and whether there is a header line

C:\>python jasonbb.py

You can also run it straight out of Texpad. Set the command to wherever you installed Python (probably C:\python23\python.exe)

Code: Select all

import csv

def foo(fileName):

    fin = open(fileName, 'r')
    fout = open(fileName + '.out', 'w')

    r = csv.reader(fin)
    w = csv.writer(fout)
    #Uncomment the following line (remove the #) if there is a header row
#    w.writerow(r.next()) #[edit]Had wrong syntax here[/url]

    for line in r:
        line[2] = str(int(line[2]) + 1)
        w.writerow(line)

def main():
    fileName = r'.\test.csv'
    foo(fileName)

if __name__ == '__main__':
    main()