2017-10-16 87 views
-1

我是一個新手蟒學習者,並陷入了這個問題......我將不勝感激任何專家的意見和幫助做一個Python腳本,可以通過在一組/行中查找特定的分隔符來讀取和搜索配置文件,如下所示。蟒蛇 - 循環搜索和特定的分隔線在文本文件

起始分隔符:^vpls\s\d+
結束分隔符:^!$

##This is an example subset of an Alcatel router config: 
! 
vpls xxx 
sdp 1.1.1.1 
backup 
lsp LSP-1 
... #some other settings here (not needed) 
exit 
sdp 2.2.2.2 
lsp LSP-2 
... #some other settings here (not needed) 
exit 
! 
vpls yyy 
sdp 1.1.1.1 
backup 
lsp LSP-1 
... #some other settings here (not needed) 
exit 
sdp 2.2.2.2 
lsp LSP-2 
... #some other settings here (not needed) 
exit 
! 

什麼,我想實現的,請注意導出爲CSV文件後,備份上的標準格式序列的最後一個項目轉移:

vpls xxx : sdp 1.1.1.1 : lsp LSP-1 : backup 
vpls xxx : sdp 2.2.2.2 : lsp LSP-2 : 
vpls yyy : sdp 1.1.1.1 : lsp LSP-1 : backup 
vpls yyy : sdp 2.2.2.2 : lsp LSP-2 : 

回答

0

我做了這個腳本。在router_cfg我存儲了您提供的輸出。

r = re.compile('(?:(vpls\w+)\s)?(sdp [\w\.]+)\s(?:(backup)\s)?(lsp [\w-]+)') 
for line in r.findall(router_cfg): 
    if line[0]: vpls = line[0] 
    print ' : '.join([vpls, line[1],line[3],line[2]]) 

如果有什麼你不明白只是問。

+0

乾杯弗朗西斯科,正則表達式似乎捕獲所需的結果,但是當我運行腳本,沒有輸出顯示。 – JessG

+0

您是否將路由器配置作爲完整字符串存儲在變量'router_cfg'中?也許你將它作爲路由器配置的每一行的字符串數組傳遞。 – FcoRodr

+0

哦原諒我,配置實際上是存儲在一個文本文件中...我只是用文件的完整路徑替換「router_cfg」。 – JessG