[Shell] sed: ファイル内の文字列を一括置換する
シェルスクリプト内で使いそうなので、ここにカテゴライズ。
[markdown]
通常、出力ファイルを指定して書き換えます。
“`prettyprinted
% sed ‘s/foo/bar/g’ input.txt > output.txt
“`
Mac OS X 上で、元ファイルを書き換えようと `sed -i` オプション付きで実行したところエラーに。
“`prettyprinted
% sed -i ‘s/foo/bar/g’ input.txt
“`
プラットフォームによっては、実行できないそう。
> * [bash – Sed command find and replace in file and overwrite file doesnt work, it empties the file – Stack Overflow](http://stackoverflow.com/questions/5171901/sed-command-find-and-replace-in-file-and-overwrite-file-doesnt-work-it-empties)
`sed -i.bak` とすると、.bak 拡張子を付けてコピーを取ってから、元ファイルを書き換えてくれます。
> * [ITmedia エンタープライズ : Linux Tips「テキストファイル内の特定文字列を一括置換させたい~Perl編~」](http://www.itmedia.co.jp/help/tips/linux/l0504.html)
“`prettyprinted
% sed -i.bak ‘s/foo/bar/g’ input.txt
“`
例えばファイル内のサーバ名を一括置換する。
“`prettyprinted
% perl -p -i.bak -e ‘s/www\./prev\.www\./g’ *.tsv
“`
[/markdown]