Search and Replace Strings in a Text File Using Wildcards
Question: Trying to do a search/replace in python using wildcards on the contents of a
text file:

If the contents of the text file looks like:

    
    
    "all_bcar_v0038.ma";
    "all_bcar_v0002.ma";
    "all_bcar_v0011.ma";
    "all_bcar_v0011.ma";
    

Looking to replace all the version numbers with v1000 to get this:

    
    
    "all_bcar_v1000.ma";
    "all_bcar_v1000.ma";
    "all_bcar_v1000.ma";
    "all_bcar_v1000.ma";
    

And have the file written out.

I've tried the below but what happens is the script only catches the first
version number, leaving the others untouched:

    
    
    def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
        line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)
    
    rigs = ['all_bcar']
    rigs_latest = ['all_bcar_v1000']
    
    old_pattern = []
    old_compiled = []
    old = []
    old_version = []
    
    for rig in range(len(rigs)):
        old_pattern.append("/" + rigs[rig] + "_(.*).ma")
        fin = open(txt_file, "r")
    
        old_compiled.append(re.compile(old_pattern[rig]))
        old.append(old_compiled[rig].search(fin.read()))
        old_version.append(old[rig].group(1).strip())
        old_rig = (rigs[rig] + "_" + old_version[rig])
        replaceAll(txt_file,old_rig,rigs_latest[rig])
    
    
    fin.close()
    

Not sure how to keep the search looping to find other versions and to avoid
the versions that have already been replaced, to skip any versions that equal
"v1000".


Answer: Your life would be vastly improved with the use of
[regexes](http://www.regular-expressions.info/python.html). You should be able
to do this in 2 lines (assuming I understand the problem correctly):

    
    
    import re
    
    for line in fileinput.input(file, inplace=1):
      re.sub(r"_v\d{4}", "_v1000", line)
    

