# -*- coding: utf8 -*-
#!/usr/bin/env python
import argparse
import os

def replacestring(old, new, path):
    f = open(path, "r")
    content = f.read()
    f.close()
    f = open(path, "w")
    content = content.replace(old, new)
    f.write(content)
    f.close()

parser = argparse.ArgumentParser(description='Find a string and replace it in files')
parser.add_argument('-R','-r', action='store_true', \\
help='walk all paths recursely', dest='R')
parser.add_argument('path', metavar='path', nargs=1, \\
help='path affected by the replacement')
parser.add_argument('oldstring', metavar='oldstring', nargs=1, \\
help='oldstring for replacement')
parser.add_argument('newstring', metavar='newstring', nargs=1, \\
help='newstring for replacement')
args = parser.parse_args()

path = args.path[0]
old = args.oldstring[0]
new = args.newstring[0]

if not os.path.exists(path):
    print "Path not found/not accessible"
    exit()

if os.path.isfile(path):
    replacestring(old, new, path)
else:
    for dirpath, dirnames, filenames in os.walk(path):
        for file in filenames:
            replacestring(old, new, os.path.join(dirpath, file))
        if not args.R: break

Published

Category

snippets

Tags