Find and replace in multiple files and add incrementing number
Question: I'm trying to replace a regex pattern in many `.cpp` files on my computer. I
need to add an incrementing number at the end of each substitution, so I chose
python to do this.

This is what I got already, but it doesn't work yet:

    
    
    import os
    import re
    i = 0
    for file in os.listdir("C:\SeparatorTest"):
        if file.endswith(".cpp"):
            for line in open(file):
                line = re.sub(r'([^\s]*)\.Separator\((.*)\)\;', r'Separator \1\_' + i += 1 + '(\1,\2);')
    

Have I missed something?


Answer: Haven't tested because I didn't think of what you are trying to replace, but
you shouldn't increment like that in the middle of your re.sub call, you need
to replace your last line of code with this :

    
    
    line = re.sub(r'([^\s]*)\.Separator\((.*)\)\;', r'Separator \1\_' + i + '(\1,\2);')
    i += 1
    

In C++ you'd just put i++ or ++i and the expression would be evaluated to i
before or after incrementation, but here I wouldn't try fancy things, python
needs to be readable and the next programmer reading your code might not guess
what you did. and there is no ++ operator in python.

Edit : And you are just reading your file, the open(file) has default "r",
which means reading, and you aren't writing anything. you need open(file, "w")
for that. and not just store the re.sub() return value in a variable, but
write it to the file.

Edit2 : Here is what I'm working on, it's not done yet, I'll edit as I find
how to get it to work :

    
    
    import os, re
    i = 0
    def replacement(i):
        i += 1
        return r'Separator \1\_' + str(i) + '(\1,\2);'
    
    for file in os.listdir("."):
        if file.endswith(".cpp"):
            for line in open(file):
                re.sub(r'([^\s]*)\.Separator\((.*)\)\;', replacement(i), line)
    

The idea is that the replacement text can be the result of a function that
should only be called when a non overlapping pattern matches, according to
[The python documentation](https://docs.python.org/2/library/re.html#re.sub)

Edit3 : I think I'll stop there, unless I get a response from you because I
have some regex and other problems I don't have time to address. Also I'm
unsure on best practice for text replacement, you should look for that, there
should be help available. Glue the whole thing together (Incrementation,
correcting your re.sub() call, open in writing mode, replace the text that
matches) and you should achieve what you were trying to do.

