Created
December 20, 2011 22:31
-
-
Save ernestom/1503598 to your computer and use it in GitHub Desktop.
Python script to search and replace uncomplicated terms recursively in a given directory, always asking for confirmation.
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
""" | |
Recursively does a search & replace in the given directory. | |
Usage: python renamer.py <dir> <search> <replace> | |
""" | |
import os | |
import re | |
import sys | |
from fabric.colors import red | |
def main(): | |
dir, search, replace = sys.argv[1:4] | |
command = 'grep -R -l %s %s' % (search, dir) | |
print command | |
files = os.popen(command).readlines() | |
for file in files: | |
search_and_replace(search, replace, file.strip()) | |
def search_and_replace(search, replace, file): | |
input = open(file) | |
lines = input.readlines() | |
input.close() | |
output = open(file, 'w') | |
for line in lines: | |
confirmation = line | |
for m in re.findall(search, line): | |
highlight = red(search) | |
confirmation = line.replace(search, highlight, 1) | |
if raw_input(confirmation) == '': | |
line = line.replace(search, replace, 1) | |
confirmation = confirmation.replace(highlight, search, 1) | |
output.write(line) | |
output.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment