2011-09-14 85 views
2

我需要幫助找到一個python解決方案來重新格式化包裝的行/重寫日誌文件,所以沒有換行符如上所述。這將讓我繼續在不間斷的線路上找到。如何打開文本文件中的包裝線,重新格式化文本文件

* .log中的每個條目都帶有時間戳記。但是,太長的行會按預期方式進行換行:換行部分也會加上時間戳。 「>」(大於)是行被包裝的唯一指示 - 發生在位置37上。>日誌來自* nix機器。

我不知道如何開始......

2011-223-18:31:11.737 VWR:tao  abc exec /home/abcd/abcd9.94/bin/set_specb.tcl -s DL 2242.500000 5 
2011-223-18:31:11.737    > -20.000000 10 
###needs to be rewritten as: 
2011-223-18:31:11.737 VWR:tao  abc exec /home/abcd/abcd9.94/bin/set_specb.tcl -s DL 2242.500000 5 -20.000000 10 

和另一

2011-223-17:40:07.039 EVT:703  agc_drift_cal.tcl: out of tolerance drift of 5.3080163871 detected! Downlink Alignmen 
2011-223-17:40:07.039    >t check required. 
###these lines deleted and consolodated as one: 
2011-223-17:40:07.039 EVT:703  agc_drift_cal.tcl: out of tolerance drift of 5.3080163871 detected! Downlink Alignment check required. 

我不知道如何開始,比其他...

for filename in validfilelist: 
    logfile = open(filename, 'r') 
    logfile_list = logfile.readlines() 
    logfile.close 
    for line in logfile_list: 

python 2.7.2

+0

+1感謝您發佈明確的要求,並在你的第一個問題的例子。 – cheeken

+0

「溢出線」是否保證其時間戳後沒有「EVT:XXX」或「VWR:YYY」? '''保證與相對於行首的位置相同? – NullUserException

+0

是的,我掃描了幾個日誌,看起來>保證了新行的開始並處於相同的位置。它沒有EVT,或其他消息先於它。 – kp1

回答

0
for filename in validfilelist: 
    logfile = open(filename, 'r') 
    logfile_list = logfile.readlines() 
    logfile.close() 
    for line in logfile_list: 
     if(line[21:].strip()[0] == '>'): 
      #line_is_broken 
     else: 
      #line_is_not_broken 
+0

或者使用'with'或至少實際調用'close' - 'logfile.close()'。 – agf

+0

o,很抱歉,我沒有太注意那些代碼,我只是複製/粘貼它。 self.notes.append(「複製/粘貼前閱讀」) – fceruti

+1

我甚至沒有讀過這個問題,所以我不知道它被複制:) – agf

0
#!/usr/bin/python 

import re 

#2011-223-18:31:11.737    > -20.000000 10 
ptn_wrp = re.compile(r"^\d+-\d+-\d+:\d+:\d+.\d+\s+>(.*)$") 

validfilelist = ["log1.txt", "log2.txt"] 

for filename in validfilelist: 
    logfile = open(filename, 'r') 
    logfile_new = open("%s.new" % filename, 'w') 
    for line in logfile: 
     line = line.rstrip('\n') 
     m = ptn_wrp.match(line) 
     if m: 
      logfile_new.write(m.group(1)) 
     else: 
      logfile_new.write("\n") 
      logfile_new.write(line) 
    logfile_new.write("\n") 
    logfile.close() 
    logfile_new.close() 

當行不是換行時寫新行。唯一的副作用是一開始就有空行。不應該是日誌分析的問題。新文件是處理結果。

0

如果你在一個filecontext包裝它這個會做的伎倆:

f = [ 
    "2011-223-18:31:11.737 VWR:tao  abc exec /home/abcd/abcd9.94/bin/set_specb.tcl -s DL 2242.500000 5", 
    "2011-223-18:31:11.737    > -20.000000 10", 
    "2011-223-17:40:07.039 EVT:703  agc_drift_cal.tcl: out of tolerance drift of 5.3080163871 detected! Downlink Alignmen", 
    "2011-223-17:40:07.039    >t check required.", 
    ] 

import re 

wrapped_line = "\d{4}-\d{3}-\d{2}:\d{2}:\d{2}\.\d{3} *>(.*$)" 

result = [""] 
for line in f: 
    thematch = re.match(wrapped_line,line) 
    if thematch: 
     result[-1] += thematch.group(1) 
    else: 
     result.append(line) 

print result