This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
# batch_replace_text.py | |
# Copyright Rishi Rawat - Feel free to distribute, but retain this line | |
# MIT license | |
import os | |
import re | |
dirpath = input("enter a path to the dir: ") | |
find = input("word to find: ") | |
replace = input("word to replace: ") | |
print "finding '%s', replacing with '%s' starting at the directory: '%s'\n\n " %(find, replace, dirpath) | |
boolean = input("Y/N") | |
class replacer: | |
def __init__(self, path, searchword, repword): | |
self.basepath = path | |
self.searchword = searchword | |
self.repword = repword | |
def replace_file(self,fname): | |
f = open(fname) | |
contents = f.read() | |
f.close() | |
contents2 = re.sub(self.searchword, self.repword, contents) | |
f = open(fname,"w") | |
f.write(contents2) | |
f.close() | |
if contents2 != contents: | |
print "\t\t changed %s" % (fname) | |
def replace_folder(self,root, dir_name): | |
oldpath = os.path.join(root,dir_name) | |
newname = re.sub(self.searchword, self.repword, dir_name) | |
newpath = os.path.join(root, newname) | |
os.rename(oldpath, newpath) | |
if oldpath != newpath: | |
print "changed %s to %s" % (oldpath, newpath) | |
return newname | |
def main(self): | |
"rename files" | |
for root, dirs, files in os.walk(self.basepath): | |
if '.git' in dirs: | |
dirs.remove('.git') # don't visit git | |
if '.svn' in dirs: | |
dirs.remove('.svn') # don't visit svn | |
for f in files: | |
fname = os.path.join(root,f) | |
self.replace_file(fname) | |
print "\n\n" | |
"do folders" | |
for root, dirs, files in os.walk(self.basepath): | |
newdirs = [self.replace_folder(root,d) for d in dirs] | |
dirs = newdirs | |
if boolean == 'Y': | |
r = replacer(dirpath, find, replace) | |
r.main() | |
No comments:
Post a Comment