たまにしか使わないといつも忘れる sed の使い方について、ではなく、Python で特定のディレクトリにある特定の拡張子のファイル(たち)に含まれる特定のパターンの文字列を置換する方法についてのメモ。
$ python
Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from os import getcwd, listdir
>>> import re
>>>
>>> cwd = getcwd()
>>> cwd
'/path/to/current/working/directory'
>>> files = listdir(cwd)
>>> files
['text001.txt', 'text002.txt', (中略) , 'text999.txt', 'program.py', 'webpage.html']
>>>
>>> for f in files:
... if '.txt' in f:
... lines = open(f).readlines()
... fobj = open(f, 'w')
... for l in lines:
... fobj.write(re.sub('some_regex', 'some_string', l))
... fobj.close()
...
>>>
これで .txt 拡張子がついたファイル(この例では text001.txt から text999.txt まで)に含まれる some_regex という正規表現パターンが some_string という文字列に置き換えられる。
関連ページ: