我在建一个网络认证实验室。有一些配置的13个设备,但由于我没有得到完全相同的设备是为材料,我必须作出一些改变的配置。
我尝试过制作Python脚本,但它与我所需要的不完全匹配。
我有一个文件,其中包含要在表单中进行的更改:
现在我必须更改的配置主要是面向对象的,所以它看起来是这样的(我已经删除了一些配置,汤姆使它变小了):
interface Serial0
description Connected to R1
frame-relay route 102 interface Serial1 201
frame-relay route 103 interface Serial2 301
frame-relay route 104 interface Serial4 401
frame-relay route 105 interface Serial5 501
frame-relay route 113 interface Serial3 311
!
interface Serial1
description Connected to R2
frame-relay route 201 interface Serial0 102
frame-relay route 203 interface Serial2 302
frame-relay route 204 interface Serial4 402
frame-relay route 205 interface Serial5 502
frame-relay route 213 interface Serial3 312
!
在那里我想替换
Serial0,Serial1/0
Serial1,Serial1/1
Serial2,Serial1/2
Serial3,Serial1/3
Serial4,Serial1/4或者像这样:
interface Serial0/0
!
interface Serial0/0.1 point-to-point
!
interface Serial0/1
!在那里我想替换
Serial0/0,Serial0/2/0
Serial0/1,Serial0/1/0现在,我用以下方法逐行执行:
def replace_all(text, dic):
for i, j in dic.iteritems():
text = re.sub("\\b"+i+"\\b", j, text)我的问题是,Serial0或Serial0/0第一次被匹配并更改为Serial1/0,但是这是由Serial1匹配的,所以我得到了Serial1/1/0。我已经尝试过用boundry (\b)、^和$,但是它似乎不起作用;我也有这样的情况:它的好键是Serial1,而不是Serial1 1/0,但是它可以使用Serial1.200。
所以它应该和我想要找到的完全匹配,或者完全符合我想要找到的+一个点和一些数字,例如。序列0/1.200
有谁知道怎么做,能为我指明正确的方向吗?
发布于 2013-09-23 15:50:22
您可以逐行处理并中断循环:
new_text=""
for line in lines:
new_text= new_text + fix_line(line)
def fix_line(line):
for i, j in dic.iteritems():
new_line = re.sub("\\b"+i+"\\b", j, line)
if new_line != line: #line changed stop loop
return new_line
return line #line didn't match
print(new_text)编辑:如果要在正则表达式上精确匹配,则应使用拆分
str_list = line.split(" ")
if len(str_list) > 4: #case the line has interface
process(str_list[4])
def process(str_to_match):
if str_to_match in dic:
return dic[str_to_match] #will get the exact match saved in the dict
return str_to_match #not in dict dont replace发布于 2013-09-23 15:43:34
一种低效但有效的方法可能是手动执行一个while循环,比如在代码中执行for循环,根据单词列表检查位置变量前面的字符串,然后替换(如果有命中),并将替换单词的长度添加到位置变量中。有点丑,但很容易,很有效。
https://stackoverflow.com/questions/18963227
复制相似问题