regex - filter a Linux log file using Python -
i want filter log file keep lines matching pattern. want python.
here's first attempt:
#!/usr/bin/env python sys import argv script, filename = argv open(filename) f: line in f: try: e = line.index("some_term_i_want_to_match") except: pass else: print(line)
how can improve to:
- save result new file of similar name (i.e., different extension)
- use regex make more flexible/powerful.
(i'm learning python. question learning python accomplishing particular result.)
ok, here's came far... how do equivalent of prepending r
in following line
re.compile(r"\s*")
where string not string literal, in next line?
re.compile(a_string_variable)
other that, think updated version job:
#!/usr/bin/env python sys import argv import re import os import argparse #requires python 2.7 or above parser = argparse.argumentparser(description='filters text file on search phrase') parser.add_argument('-s','--search', help='search phrase or keyword match',required=true) parser.add_argument('-f','--filename', help='input file name',required=true) parser.add_argument('-v','--verbose', help='display output 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) open(original_file) fi: open(new_file, 'w') fo: line in fi: result = regex_c.search(line) if(result): fo.write(line) if(verbose): print(line)
can improved?
well, know, have answered of questions :)
for regular expression matching use re
module (the doc has pretty explanatory examples).
you have made use open()
function opening file. use same function open files writing, provide corresponding mode
parameter ("w" or "a" combined "+" if need, see help(open)
in python interactive shell). that's it.
Comments
Post a Comment