5
4

More than 5 years have passed since last update.

sed で置換

Last updated at Posted at 2015-03-09

sed でファイル内の特定の文字を、改行を含む別の文字列に置き換えたい時のメモ。

追記
sed には a(append) コマンド、 i(insert) コマンドがあるようで、こちらでも可能でした。
コメントで教えて頂きました。ありがとうございます!

$ echo "hoge" | sed -e '/hoge/a fuga'
hoge
fuga

$ echo "hoge" | sed -e '/hoge/i fuga'
fuga
hoge

追記ここまで

hoge の後に、fuga を追加したい場合

$ echo "hoge" | sed -e 's@hoge@\0\nfuga@'
hoge
fuga

hoge の前に、fuga を追加したい場合

$ echo "hoge" | sed -e 's@hoge@fuga\n\0@'
fuga
hoge

hoge の前に、fugahogeraを追加したい場合

$ echo "hoge" | sed -e 's@hoge@fuga\nhogera\n\0@'
fuga
hogera
hoge

sed で改行を含む置換は面倒と散見されたけど、
この方法だと普通に \n でいけるみたい。
文字中の ()[]\(\)\[\] とエスケープが必要。

$ sed --version
GNU sed version 4.2.1

参考

5
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4