Use regex to add string to different multilines with simularities
Question: I have a .txt file with multiple lines (Different yet simular for each one)
that I want to add a "*.tmp" at the end.

I'm trying to use python2.7 regex to do this.

Here is what I have for the python script:

    
    
    import sys
    import os
    import re
    import shutil
    
    #Sets the buildpath variable to equal replace one "\" with two "\\" for python code to input/output correctly
    buildpath = sys.argv[1]
    buildpath = buildpath.replace('\\', '\\\\')
    
    #Opens a tmp file with read/write/append permissions
    tf = open('tmp', 'a+')
    
    #Opens the selenium script for scheduling job executions
    with open('dumplist.txt') as f:
    #Sets line as a variable for every line in the selenium script
        for line in f.readlines():
        #Sets build as a variable that will replace the \\build\path string in the line of the selenium script
            build = re.sub (r'\\\\''.*',''+buildpath+'',line)
            #Overwrites the build path string from the handler to the tmp file with all lines included from the selenium script
            tf.write(build)
    #Saves both "tmp" file and "selenium.html" file by closing them
    tf.close()
    f.close()
    #Copies what was re-written in the tmp file, and writes it over the selenium script
    shutil.copy('tmp', 'dumplist.txt')
    #Deletes the tmp file
    os.remove('tmp')
    #exits the script
    exit()
    

Current File Before Replacing the Line:

    
    
    \\server\dir1\dir2\dir3
    
    DUMP3f2b.tmp   
               1 File(s)  1,034,010,207 bytes
    
    \\server\dir1_1\dir2_1\dir3_1
    
    DUMP3354.tmp   
               1 File(s)    939,451,120 bytes
    
    \\server\dir1_2\dir2_2\dir3_2
    

Current file after replacing string:

    
    
    \*.tmp
    
    DUMP3f2b.tmp   
               1 File(s)  1,034,010,207 bytes
    
    \*.tmp
    
    DUMP3354.tmp   
               1 File(s)    939,451,120 bytes
    
    \*.tmp
    

Desired file after replacing string:

    
    
    \\server\dir1\dir2\dir3\*.tmp
    
    DUMP3f2b.tmp   
               1 File(s)  1,034,010,207 bytes
    
    \\server\dir1_1\dir2_1\dir3_1\*.tmp
    
    DUMP3354.tmp   
               1 File(s)    939,451,120 bytes
    
    \\server\dir1_2\dir2_2\dir3_2\*.tmp
    

If anyone could help me in solving this that would be great. Thanks :)


Answer: You should use capturing groups:

    
    
    >>> import re
    >>> s = "\\server\dir1\dir2\dir3"
    >>> print re.sub(r'(\\.*)', r'\\\1\*.tmp', s)
    \\server\dir1\dir2\dir3\*.tmp
    

Then, modify `build = re.sub (r'\\\\''.*',''+buildpath+'',line)` line this
way:

    
    
    build = re.sub (r'(\\.*)', r'\\\1%s' % buildpath, line)
    

Also, you shouldn't call `readlines()`, just iterate over `f`:

    
    
    for line in f:
    

