1.内容简介:
在Linux中,可以用sed进行文本的查找和替换。再结合python,可以将整个项目的关键文本进行替换。
2. 脚本程序:将"./test_a"目录下的(保括子目录)下的所有文件内容中的“green”改为“blue”
程序清单:
import os
##第一步、加载文件,获取文件路径以及标签
'''
fstr:文件路径
old_str:查找的字符串
new_str:替换后的字符串
'''
def build_sed_cmd(fstr,old_str,new_str):
sed_cmd = "sed -i " + "\"" + "\""+ " "+ "\"" + "s/" + old_str + "/" + new_str + "/g" + "\"" + " " + fstr
return sed_cmd
def replace_str(path,dir,old_str,new_str):
dirs = os.listdir(path)
for a in dirs:
# print(a)
fstr = path+"/"+a
# print(fstr)
print(os.path.isfile(fstr))
#
# sed -i "" "s/green/blue/g" abc_sed/*.txt //green->blue
if os.path.isfile(fstr):
t = '$'
if t in fstr:
split_arr = fstr.split('$')
res_str = ""
for s in split_arr:
res_str = res_str + s + "\$"
print("res_str:" + res_str)
fstr = res_str[:-2]
print("fstr:" + fstr)
#sed_cmd = "sed -i " + "\"" + "\""+ " "+ "\"" + "s/green/blue/g" + "\"" + " " + fstr
sed_cmd = build_sed_cmd(fstr,old_str,new_str)
print("sed_cmd:" + sed_cmd)
status=os.system(sed_cmd)
print(status)
allpath.append(dirs)
if dir!="":
lllables.append(dir)
else:
replace_str(str(path)+"/"+str(a),a)
##循环遍历这个文件夹
return allpath,lllables
if __name__ == '__main__':
print("main==begin===")
test_path="./test_a"
allpath=[]
lllables=[]
oldstr = "green"
newstr = "blue"
[allpath,lllables]=replace_str(test_path,"",oldstr,newstr)
print("main==end===")
运行结果:
将"./test_a"目录下的(保括子目录)下的所有文件内容中的“green”改为“blue”
while_loop.py
aibook@aibookdeMacBook-Pro chaper % cat test_a/a.txt
red yello blue green orange
whiteblackgreenred aibook@aibookdeMacBook-Pro chaper % python replace_str.py
main==begin===
True
fstr:./test_a/b.txt
sed_cmd:sed -i "" "s/green/blue/g" ./test_a/b.txt
0
True
fstr:./test_a/a.txt
sed_cmd:sed -i "" "s/green/blue/g" ./test_a/a.txt
0
main==end===
aibook@aibookdeMacBook-Pro chaper % cat test_a/a.txt
red yello blue blue orange
whiteblackbluered aibook@aibookdeMacBook-Pro chaper % cat test_a/b.txt
blue orange
a blue red blue
说明:
使用递归调用replace_str方法。
python脚本,事半功倍。