[英]Matching pattern in Python
我有一個目錄“ / pcap_test”,其中包含幾個日志文件。 每個文件都有一個類似的模式:
包長度:1(358字節),壽命:1,應用程序:iTunes(INTO),狀態:終止,堆棧:/ ETH / IP / UDP / itunes,錯誤:無
Pkt:2(69字節),LIFE:2,App:zynga(INTO),狀態:INSPECTING,堆棧:/ ETH / IP / UDP,錯誤:None
包長度:3(149字節),壽命:2,應用程序:比薩店(INTO),狀態:已終止,堆棧:/ ETH / IP / UDP / pizzeria,錯誤:無
在這種情況下,我希望輸出是第二行,因為“應用程序”中的內容不在“堆棧:”中
我寫了一個小的Python腳本來遍歷目錄,打開每個文件並輸出輸出:
import os
list = os.listdir("/home/test/Downloads/pcap_test")
print list
for infile in list:
infile = os.path.join("/home/test/Downloads/pcap_test" , infile)
if os.path.isfile(infile):
str = file(infile, 'r').read()
print str
我以某種方式使用grep獲得了輸出,但無法在python腳本中使用相同的輸出。 它類似於:
grep -vP 'App: ([^, ]*) \(INTO\).*Stack: .*\1.*$' xyz.pcap.log | grep -P 'App: ([^, ]*) \(INTO\)'
由於我已經有了名為“ str”的文件,因此我想使用該文件而不是單個日志文件來獲取輸出。
在這方面的任何幫助將不勝感激。
首先,我建議不要使用諸如str
之類的變量名,因為這是String
原始數據類型的Python名稱。
由於grep是一個命令行正則表達式工具,並且由於您已經擁有一個有效的正則表達式,因此您所要做的就是學習使用Python的re
模塊 。
捕獲grep的-v
行為有點困難。 我建議逐行讀取文件並僅在不匹配第一個正則表達式但匹配第二個正則表達式時打印該行,如下所示:
if os.path.isfile(infile):
with file(infile, 'r') as logFile: #this will close the file pointer automatically when you finish
for line in logFile: #read logFile one line at a time
firstReMatch = re.match(r'App: ([^, ]*) \(INTO\).*Stack: .*\1.*$', line) #check if this line matches your first regex
secondReMatch = re.match(r'App: ([^, ]*) \(INTO\)', line) #check if this line matched your second regex
if secondReMatch and not firstReMatch: #"not" to capture the inverse match
print line #print the line.
根據您的數據,您可能需要使用re.search()
而不是re.match()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.