2014-02-06 56 views
1

我想過濾日誌文件以保持所有行匹配特定模式。我想用Python來做到這一點。使用Python過濾Linux日誌文件

這是我第一次嘗試:

#!/usr/bin/env python 

from sys import argv 

script, filename = argv 
with open(filename) as f: 
    for line in f: 
     try: 
      e = line.index("some_term_I_want_to_match") 
     except: 
      pass 
     else: 
      print(line) 

我怎樣才能提高這:

  • 結果保存到類似的名稱(例如,不同的擴展名)
  • 使用的一個新的文件正則表達式使其更加靈活/強大。

(我剛開始學習Python的。這個問題是儘可能多地學習Python的,因爲它是實現這一特定結果。)

確定,這裏就是我想出了那麼遠,但你如何做以下行

re.compile(r"\s*") 

在字符串一個字符串前置一個r如,在下一行的相同呢?

re.compile(a_string_variable) 

除此之外,我覺得這個更新版本做這項工作:

#!/usr/bin/env python 

from sys import argv 
import re 
import os 
import argparse #requires Python 2.7 or above 

parser = argparse.ArgumentParser(description='filters a text file on the search phrase') 
parser.add_argument('-s','--search', help='search phrase or keyword to match',required=True) 
parser.add_argument('-f','--filename', help='input file name',required=True) 
parser.add_argument('-v','--verbose', help='display output to the screen too', required=False, action="store_true") 
args = parser.parse_args() 

keyword = args.search 
original_file = args.filename 
verbose = args.verbose 

base_file, ext = os.path.splitext(original_file) 
new_file = base_file + ".filtered" + ext 

regex_c = re.compile(keyword) 

with open(original_file) as fi: 
    with open(new_file, 'w') as fo: 
     for line in fi: 
      result = regex_c.search(line) 
      if(result): 
       fo.write(line) 
       if(verbose): 
        print(line) 

這能容易地改進?

+2

爲什麼不使用'grep'?如果你想使用正則表達式並堅持用Python寫這個,看看're'模塊。 – Blender

+1

在我看來,這裏不需要'嘗試......除外'。 – squiguy

+0

我更新了我的問題。我想用Python做這件事,因爲我正在學習Python。 – MountainX

回答

1

嗯,你知道,你已經回答了你的大部分問題已經自己:)

對於正則表達式匹配使用re module(DOC的有漂亮的解釋性的例子)。

您已經利用open()功能打開文件。對於打開的文件使用相同的函數進行寫入,只需提供相應的mode參數(如果需要,請參閱「w」或「a」,如果需要,請參閱help(open))。而已。

+1

...並使用[os.path](http://docs.python.org/3.3/library/os.path.html)模塊更改文件擴展名。 – Simon

+0

我更新了我的問題 – MountainX

+0

那麼,「改進」不是一個正確的詞來描述您的需求。如果它做到了你想要的,那就不應該改進。如果你需要別人,你應該明確地闡述它。我會通過在一個語句中合併文件打開來降低嵌套級別,但這需要一個實現[Context Manager protocol]的對象(http://docs.python.org/2/reference/datamodel.html#with-statement-上下文經理)。或者簡單地使用'try:f = open(「original」)... finally:f.close()...'這意味着幾乎與'with'語句相同 – user3159253