findreplace.py

download
#!/usr/bin/env python
import os , sys, tempfile, string, fnmatch


def listFiles(root, patterns='*', recurse=0, return_folders=0):

    # Expand patterns from semicolon-separated string to list
    pattern_list = patterns.split(';')
    # Collect input and output arguments into one bunch
    class Bunch:
        def __init__(self, **kwds): self.__dict__.update(kwds)
    
    arg = Bunch(recurse=recurse, pattern_list=pattern_list, return_folders=return_folders, results=[])
    
    def visit(arg, dirname, files):
        #Append to arg.results all relevant files (and perhaps folders)
        for name in files:
            fullname = os.path.normpath(os.path.join(dirname, name))
            if arg.return_folders or os.path.isfile(fullname):
                for pattern in arg.pattern_list:
                    if fnmatch.fnmatch(name, pattern):
                        arg.results.append(fullname)
                        break
        # Block recursion if recursion was disallowed
        if not arg.recurse: files[:]=[]
        
    os.path.walk(root, visit, arg)
    
    return arg.results


nargs = len(sys.argv)


if not 5 == nargs:
    print "zu wenig Argumente! richtig: findreplace.py 'Ordner' 'wildcard1;wildcard2' 'eingangsstring' 'ersatzstring'"

else:
    countfiles = 0
    changefiles = []
            
    #rtext = sys.argv[1]
    sstring = sys.argv[3]
    rstring = sys.argv[4]
    for i in listFiles(os.path.join(os.getcwd(),sys.argv[1]),sys.argv[2]):
        
        test = os.popen('grep \''+sstring+'\' '+i)
        
        if test.read():
            countfiles = countfiles + 1
            changefiles.append(i)
            tmpf=tempfile.mktemp('txt')
            outtmp = open(tmpf,'w')
            infile=open(i,'r')
            for s in infile.xreadlines():
                outtmp.write(s.replace(sstring,rstring))
                
            infile.close()
        #	os.rename(i,i+'_del')
            outnew = open(i,"w")
            outtmp.close()
            outtmp = open(tmpf,'r')
            for s in outtmp.xreadlines():
                outnew.write(s)
            outtmp.close()
            os.unlink(tmpf)
            outnew.close()
            
            
        test.close()
        
    print "%s files veraendert:"% countfiles
    for f in changefiles:
        print f.replace(os.getcwd(),'') +'\n'