Pythonで複数のlog exportを検索する4 / 4

抽出したログを端末とファイルへ出す

転送元アドレスの欄だけを照合し、一致したログ行を端末とファイルの両方に残します。次は、test_log.log に fwd="192.168.100.100" と fwd="192.168.100.10" の行があり、output ディレクトリーが作成済みの場合です。

target = 'fwd="192.168.100.100"'
with open("test_log.log", encoding="utf-8") as source:
    with open("output/parsed_host.log", "w", encoding="utf-8") as out:
        for line in source:
            if target in line:
                print(line, end="")
                out.write(line)

端末と出力ファイルに残るのは、末尾が .100 の行だけです。末尾まで引用符で囲んだ値を探すため、.10 や .1000 には一致しません。

📘 Python:openとprint

学習パスへ
参考資料