ファイル内の文字列を変換する

ファイル内の特定の文字列を変換したい場合、sedコマンドを使用する。

  • コマンド
sed -e 's/変換前の文字列/変換後の文字列/g' 入力ファイル > 出力ファイル

下記の内容のファイルがあるとする。ファイル名はfruit.txtとする。
---------------------------
apple orange grape apple
orange grape apple orange
grape apple orange grape
---------------------------

ファイル内の「apple」という文字列を「りんご」に変換し、fruit_next.txtという名前のファイルに出力する場合、次のようなコマンドを実行する。

sed -e 's/apple/りんご/g' fruit.txt > fruit_next.txt

fruit_next.txtの内容
---------------------------
りんご orange grape りんご
orange grape りんご りんご
grape りんご orange grape
---------------------------

gを除いた場合、それぞれの行の最初にマッチした文字列のみを変換する。

sed -e 's/apple/りんご/' fruit.txt > fruit_next.txt

fruit_next.txtの内容
---------------------------
りんご orange grape apple
orange grape りんご apple
grape りんご orange grape
---------------------------