Last active
August 22, 2018 17:17
-
-
Save templateaholic10/ee937d91b1ad8ffa57307eaf43e8d1f9 to your computer and use it in GitHub Desktop.
sedのPython実装
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
''' | |
Pythonでsedライクなコマンドライン処理を実現する. | |
Pysed#line_procをoverrideしたメソッドをコールする. | |
対話環境では以下のようにする: | |
def line_proc(line): | |
return line | |
# 標準出力 | |
with open(finname, 'r') as fin: | |
for line in fin: | |
print(line_proc(line.rstrip())) | |
# ファイル出力 | |
with open(finname, 'r') as fin: | |
with open(foutname, 'w') as fout: | |
for line in fin: | |
print(line_proc(line.rstrip()), file=fout) | |
''' | |
import fileinput | |
class Pysed(object): | |
''' | |
sedを実現するクラス. | |
Pysed#line_procをoverrideしてPysed#runで実行する. | |
''' | |
def __init__(self): | |
pass | |
def line_proc(self, line): | |
return line | |
def run(self): | |
for line in fileinput.input(): | |
print(self.line_proc(line.rstrip())) | |
if __name__ == '__main__': | |
pysed = Pysed() | |
pysed.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment