python2.7
描述:
删除多个配置文件当中的某些子项(
删除 192.168.2.xxx 段的配置项),配置文件格式内容如下:
-
define host{
-
use linux-server
-
host_name TM_2_202
-
alias 202
-
address 192.168.2.202
-
}
-
-
define host{
-
use linux-db
-
host_name TM_2_187
-
alias 187
-
address 192.168.2.187
-
}
-
-
define host{
-
use linux-db
-
host_name TM_22_189
-
alias 189
-
address 192.168.22.189
-
}
被删除满足条件的子项之后的结果如下:
-
define host{
-
use linux-db
-
host_name TM_22_189
-
alias 189
-
address 192.168.22.189
-
}
实现如下:
-
#!/usr/bin/env python
-
#coding: utf-8
-
-
import os
-
import re
-
-
-
def create_new_cfg(old_path,new_path):
-
for filename in os.listdir(old_path):
-
if os.path.isfile(filename) and re.search('^tm_',filename) and re.search('hosts.cfg',filename):
-
old_fi = open(filename,'r')
-
new_fi = open(os.path.join(new_path,'new_'+filename),'w')
-
li=[]
-
for line in old_fi.readlines():
-
if line.split():
-
li.append(line)
-
if re.search('}',line):
-
if re.search('_2_',li[2]):
-
li = []
-
continue
-
for s in li:
-
new_fi.write(s)
-
li = []
-
-
old_fi.close()
-
new_fi.close()
-
-
-
if __name__ == '__main__':
-
create_new_cfg('./','/tmp')
脚本解析:
① line.split() 判断是否为空行(='\r' '\n' ' ' '\t' 等为分隔符 会返回空列表)
② re.search('}',line) 表示读取到某行包含'}' 的时候,意味着到了子项的结束(子项已经存在于li列表中),在进行进一步的判断
③ 其中os.path.isfile 以及 os.listdir ,os.path.join 方法都是对文件系统的相关操作
拓展:
① 判断空行的方法
1> line.split()
所有的空格、制表符、回车符当作分隔符,并过滤掉空串
2> line.strip() == '' 删除line的头尾中的'\t' '\n' '\r' ' '
②python的正则匹配
1> re.search(pattern,str)
在字符串内查找模式匹配,只到找到第一个匹配然后返回,如果字符串没有匹配,则返回None。
2> re.match(pattern,str)
从字符串的开始匹配一个模式,如果字符串开始不符合正则表达式,则匹配失败,函数返回None。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31385648/viewspace-2135786/
,如需转载,请注明出处,否则将追究法律责任。