Find And Replace Multi-line Strings Of Files In A Dir

Xah Lee, 2005-02-03.

Previously we had code that find & replaces strings in a dir. See http://xahlee.org/perl-python/find_replace_dir.html

Now suppose in your html file, you want to replace “<body>\n\n<table>” by some other code. The thing is that the find string span several lines. So the old code won't work because it process one line at a time. One solution would be to read the file content all at once as a string. The disadvantage of reading all file content one-shot is that if a file is very large, than this would be a problem. It would only be a problem if the file is some hundreds of megabytes. (it depends on how much memory your computer has)

# -*- coding: utf-8 -*-

import os,sys

mydir= '/Users/t/web/x'

findStr='''<body>

<table>'''
repStr='''<body>\n<P>new stuff!</p>\n<table>'''


def replaceStringInFile(findStr,repStr,filePath):
   "replaces all findStr by repStr in file filePath"
   tempName=filePath+'~~~'
   input = open(filePath)
   output = open(tempName,'w')

   s=input.read()
   output.write(s.replace(findStr,repStr))
   output.close()
   input.close()
   os.rename(tempName,filePath)
   print filePath

def myfun(dummy, dirr, filess):
    for child in filess:
        if '.html' == os.path.splitext(child)[1] and os.path.isfile(dirr+'/'+child):
            replaceStringInFile(findStr,repStr,dirr+'/'+child)
os.path.walk(mydir, myfun, 3)

For a full-featured script that does find-replace in Perl, see: Find & Replace on Multiple Files with Perl


See also:


Page created: 2005-01.
© 2005 by Xah Lee.
Xah Signet