Humanity

Edit the world by your favorite way

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

ある文字列をファイルの特定行に挿入するコマンド - 元RX-7乗りの適当な日々
元記事はこちら。

元ファイル

$ cat test.txt 
line1
line2
line3

2行目に挿入

$ vim -u NONE -i NONE -c "2put! ='hoge'" -c wq test.txt
$ cat test.txt
line1
hoge
line2
line3

2行目直下に挿入

$ vim -u NONE -i NONE -c "2put ='hoge'" -c wq test.txt
$ cat test.txt
line1
line2
hoge
line3

"line2"の行前に挿入

$ vim -u NONE -i NONE -c "/^line2$" -c "put! ='hoge'" -c wq test.txt
$ cat test.txt
line1
hoge
line2
line3

"line2"の行後に挿入

$ vim -u NONE -i NONE -c "/^line2$" -c "put ='hoge'" -c wq test.txt
$ cat test.txt
line1
line2
hoge
line3

注意点

  1. vimとか書いてありますが多分viでも動きます
    1. つまりこの記事の「vim」を「vi」に変えても動きます
  2. 「-u NONE -i NONE」はプラグインと.vimrcの読み込みと.viminfoへの書き込みを抑制するためのおまじない
  3. 「-c wq」してることからもわかる通り、test.txtを破壊的に変更します
    1. 破壊的に変更せずパイプからパイプへ処理できるiexなんてのもあります