批量替换文件夹下所有文件内容脚本(shell,php,python)
九月 14, 2009 | linux, php, python | RSS 2.0
批量替换一个文件夹下的字符或者其他的应该经常可以见到,近期读《卓有成效的程序员》有点感触,他提到了一些可以加快工作效率的容易让人忽略的小细节,加速法则,专注法则,自动化 法则,规范化法则。那这个批量替换应该属于自动化法则,有时候文件特别多的是很,替换是个非常容易烦人的事情。显然这些应该是计算机做的事情,下面给出以上三个版本:
shell:
sed跨行需要使用参数:N等控制,这里不适用,忘记。
shell学了个皮也不皮,毛也不毛
for i in `find . -name "*.html"`
do
sed "s|<\!--{if \!empty(\$this->_visiteduser->_gender)&& \(\$this->_visiteduser->_gender\)=='m'}-->他<\!--{else}--> 她<\!- -{/if}-->|{\1}|g" $i > $i-new
mv $i $i-old
mv $i-new $i
done当然你可以用sed的i直接替换,尽量替换前做个备份。
python的批量替换脚本:
刚开始学写的特别烂:
import os import re def getHtmlFile(rootdir): allfile=[] for parent, dirnames, filenames in os.walk(rootdir): for filename in filenames: #if os.path.isfile(os.path.join(0) allfile.append(os.path.join(parent, filename)) return allfile def replace(filename): file_object = open(filename) try: all_the_text = file_object.read( ) finally: file_object.close( ) ''' grouped_word = re.compile('<div id="header">([\s\S]*)?</div>') all_the_text = re.sub(r'xxxxxxxxxxxxxxxxxx',all_the_text); ''' all_the_text = re.sub('<div id="header">[\s\S]+?</div>','header',all_the_text); all_the_text = re.sub('<div id="footer">[\s\S]+?</div>','footer',all_the_text); #all_the_text = re.sub('\r','',all_the_text); open(filename, 'w').write(all_the_text) file=getHtmlFile('/home/liufb/studypython/gonglue'); test = re.compile("\.html$", re.IGNORECASE) file = [f for f in file if test.search(f)] for i in file: print i+"\n" replace(i)
学的时间相对比较长,但是依旧比较烂:
function changefile($filename) { global $text1; global $text2; $file = file_get_contents($filename); $file2 = preg_replace('@<div id="header">([\s\S]*)?</div>@iU',$text1,$file); $file3 = preg_replace('@<div id="footer">([\s\S]*)?</div>@iU',$text2,$file2); $file3 = preg_replace('@\r@iu','',$file3); file_put_contents($filename,$file3); } function getFile($dirname) { if ($handle = opendir($dirname)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $file=$dirname.'/'.$file; if(is_file($file) && substr($file,-5) =='.html') { //echo $file."\n"; changefile($file); }else if(is_dir($dirname.'/'.$file)) { $dirscan = realpath($file); //$dirscan = $dirname.'/'.$file; //echo $dirscan."\n"; getFile($dirscan); } } } } closedir($handle); } getFile('.');