置換スクリプト

ファイルを読み込んで特定の文字列を置換するスクリプト

./replace.py

置換処理自体はreplace関数を使っています

#!/usr/bin/python
# coding:utf-8

import sys

text_old = sys.argv[1]    # 置換前文言
text_new = sys.argv[2]    # 置換後文言

input_file  = sys.stdin   # 変換元ファイル
output_file = sys.stdout  # 変換後出力先ファイル

# ファイルをロード
input_file = open(sys.argv[3])
output_file = open(sys.argv[4], 'w')

# 置換
for s in input_file:
    # 1行ずつ処理します
    output_file.write(s.replace(text_old,text_new))

# 後片付け
output_file.close()
input_file.close()
処理概要
[farmedgeek@Mint ~/python]$ cat input.txt 
spam
hoge
ham
hoge
spam
ham
eggs
hoge and hoge
hoge
spam and hoge
[farmedgeek@Mint ~/python]$ 

こういうファイルに対して
"hoge"の文字列を"spam"に置換してみます。

実行結果
[farmedgeek@Mint ~/python]$ ./replace.py hoge spam input.txt output.txt
[farmedgeek@Mint ~/python]$ cat output.txt 
spam
spam
ham
spam
spam
ham
eggs
spam and spam
spam
spam and spam
[farmedgeek@Mint ~/python]$