Welcome, guest | Sign In | My Account | Store | Cart

This script go thru directory tree and looks for files off specified pattern, and then replace in those files string with new one, overwriting old file without backups

Python, 16 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import os.path
import fnmatch
import fileinput
import re
import string

def callback(arg, directory, files):
    for file in files:
        if fnmatch.fnmatch(file,arg):
            for line in fileinput.input(os.path.abspath(os.path.join(directory, file)),inplace=1):
                if re.search('.*theunderdogs.*', line): # I changed * to .* but it would probably work without this if
                    line = string.replace(line,'theunderdogs','the-underdogs') # old string , new string
                print line,
            

os.path.walk("c:/windows/favorites", callback, "*.url") # Directory  you are looking under, and file pattern

I hade loots of favorites containing www.theunderdosg.org , but they unfortunately changed their address to www.the-underdogs.org So I need to change every instance off it. since I like python I made this little dirty script that do joust that. This is mix off few modified examples found in python news groops. It is weary simple and has no error handling. If you have bunch off files containing one phrase that need to bee changed than you can use this script and make it. And don't forget to backup !

2 comments

Drew Perttula 19 years, 7 months ago  # | flag

a perl way to do it (for educational purposes only). This is a fine illustration of fileinput which I was not familiar with.

However, it should be noted that perl treats this kind of operation as a common case, and the entire callback function can be expressed in one short line. Furthermore, you can call that line as a command line option, like this:

perl -pi -e 's/theunderdogs/the-underdogs/g' **/*.url

(-p means process every line of the files, -i means in-place, -e means execute this command) The */.url is a special zsh trick. If you don't run zsh, use something like this:

find favorites/ -name '*.url' | xargs perl -pi -e '...'

Perl even has a shortcut for making backups of the files it processes. Use "-pi.bak" to copy inputfile to inputfile.bak before processing.

Also, I think the python program meant to say '.theunderdogs.' (or just 'theunderdogs'. That's the functionality of my perl version.

Ivan Brkanac (author) 19 years, 7 months ago  # | flag

Right. I fixed * to .* but I think it would probably work without it only slower