ある文字列をファイルの特定行に挿入するコマンド

Linux等で、ファイルの特定の行に、ある文字列を挿入(追加)したい時のコマンド(sed)サンプルを備忘録的に。

前提

こんなファイルがあります。

$ cat test.txt 
line1
line2
line3

2行目に挿入

$ sed -e "2i hoge" test.txt 
line1
hoge
line2
line3

2行目直下に挿入

$ sed -e "2a hoge" test.txt 
line1
line2
hoge
line3

"line2"の行前に挿入

※この辺の正規表現は、要件に応じて適当に変えてー。

$ sed -e "/^line2$/i hoge" test.txt 
line1
hoge
line2
line3

"line2"の行後に挿入

$ sed -e "/^line2$/a hoge" test.txt 
line1
line2
hoge
line3


sed & awkプログラミング 改訂版 (A nutshell handbook)

sed & awkプログラミング 改訂版 (A nutshell handbook)