Skip to content

Instantly share code, notes, and snippets.

@junfenglx
Created April 7, 2015 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junfenglx/1347e25864e4d8239b5e to your computer and use it in GitHub Desktop.
Save junfenglx/1347e25864e4d8239b5e to your computer and use it in GitHub Desktop.
replace one word with another recursively
#!/usr/bin/env python
# encoding: utf-8
'''
replace one word with another recursively
'''
import os
import subprocess
import os.path
import argparse
import traceback
def visitor(filepath, old_str, new_str):
new_lines = []
has_old_str = False
with open(filepath, "r") as f:
for line in f:
if line.find(old_str) >= 0:
has_old_str = True
line = line.replace(old_str, new_str)
new_lines.append(line)
if has_old_str:
with open(filepath, "w") as f:
print ("repaire %s" % filepath)
f.write(''.join(new_lines))
def is_binary(filename):
cmd = "file -bi %s" % filename
output = subprocess.getoutput(cmd)
binary = False
try:
if output.split(";")[-1].split("=")[-1] == "binary":
binary = True
except Exception as e:
pass
return binary
def walk(root, old_str, new_str, exclude):
for root, dirs, filenames in os.walk(root):
if exclude:
if exclude in dirs:
dirs.remove(exclude)
for filename in filenames:
filepath = os.path.join(root, filename)
if is_binary(filepath):
continue
try:
visitor(filepath, old_str, new_str)
except Exception as e:
traceback.print_exc()
print("failed on %s" % filepath)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-R", "--ROOT", required=True, dest="root",
help="set root dir to scan")
parser.add_argument("-O", "--OLD", required=True, dest="old",
help="old string")
parser.add_argument("-N", "--NEW", required=True, dest="new",
help="new string")
parser.add_argument("-E", "--EXCLUDE", dest="exclude",
help="new string")
args = parser.parse_args()
root = args.root
if not os.path.isdir(root):
parser.print_help()
old_str = args.old
new_str = args.new
exclude = args.exclude
walk(root, old_str, new_str, exclude)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment