缘由和需求大概描述是这样,有个提供接口服务老站点A要下线,但还有站点B还在调用这个接口,要切换到新接口,由于站点B历史悠久估计有10年时间,经很多人手站点代码和文件有5.4G大小内有很多目录文件。现在要站点B内所有目录下所有'*.php' 文件内接口url为"http://xx.xxxx.com/outer/Interface.php?w=$word&n=$num&out=xml""http://xx.xxxx.com/?c=api&s=$word&out=xml&page=1&pagesize=$num" ;当时想使用shell的find,for,sed来处理,由于url里面有很多特殊字符,即使我做了转义了还是无法使用sed进行替换,暂没时间查很多sed的资料,就使用熟悉的python来进行处理。

  在我调试的时候发现,有目录文件大小为5.5G的文件使用os.walk()查找所有下"*.php"时使用4分多钟,python调用shell的find命令时才用40秒。下面是代码,希望脚本的思路和写法给大家一些提示或帮助。(如果哪位有sed替换有特殊字符url,望不吝赐教)

#/usr/bin/python#coding:utf-8"""To update all directory php file for new interfaces url"""__author__ = 'Qfeian@20140307'import fileinputimport  osdef replace_str(filepath, old, new):    for line in fileinput.input(filepath, inplace=True):        line = line.rstrip().replace(old, new)        print lineold_str = """http://xx.xxxx.com/outer/Interface.php?w=$word&n=$num&out=xml"""new_str = """http://xx.xxxx.com/?c=api&s=$word&out=xml&page=1&pagesize=$num""""""pattern = '.php'rootdir = '/data/app/ms.www.xxxx.com'for root, subfolders, files in os.walk(rootdir):    for name in files:        if name.find(pattern) != -1:            filedir = os.path.join(root, name)            #print filedir            replace_str(filedir, old_str, new_str)"""if __name__ == "__main__":    cmd = "find /data/app/ms.www.xxxx.com -name '*.php' "    filedirlist = os.popen(cmd)    for filedir in filedirlist.readlines():        filedir = filedir.strip('\n')#去掉每行末尾的换行符        #print filedir        replace_str(filedir, old_str, new_str)