awk組み込みのinplaceは置換後のバックアップファイルを取るときに非常に便利です。
公式では、
The inplace extension emulates GNU sed’s -i option, which performs “in-place” editing of each input file. It uses the bundled inplace.awk include file to invoke the extension properly:
とあります。
流石は日々のテキスト処理のために開発された言語。
*実際のところ
以下のようなテキストがあったとします。
$ cat sample.txt This is my dog, whose name is Frank. This is my fish, whose name is George. This is my goat, whose name is Adam.
これについて、ThisをThatに変えたいが改変前のデータは.bakで残しておきたい……なんてアリガチなケースを考えます。
この場合、以下のようにします。
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{ gsub(/This/,"That")}; {print}' sample.txt
特徴的なのは「INPLACE_SUFFIX」変数です。
こいつを指定してやれば、処理後にバックアップを取ってくれます。クッソ便利。
処理が終わったあと、実際に確認すると……ちゃんと、二つのファイルが残ってますね。
$ head sample.txt sample.txt.bak ==> sample.txt <== That is my dog, whose name is Frank. That is my fish, whose name is George. That is my goat, whose name is Adam. ==> sample.txt.bak <== This is my dog, whose name is Frank. This is my fish, whose name is George. This is my goat, whose name is Adam.
この程度なら、他の軽量言語でガリガリ書くのもいいですが。
参考もと
- Effective Awk