7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

vimで検索条件に一致する行を加工する方法

Posted at

ログファイルなど大量のテキストを加工する場合に置換だけでは不十分なケースがたまにありますが
加工したい行を検索条件で指定できる場合 global コマンドが役に立ちます。

例えばこんなログ.log
May 20 00:00:00 test-main kernel: (guest)aaaaa
May 20 00:00:00 test-main kernel: (guest)bbbbb
May 20 00:00:00 test-main kernel: (root)aaaaa
May 20 00:00:00 test-main kernel: (guest)ccccc
May 20 00:00:00 test-main kernel: (root)bbbbb
May 20 00:00:00 test-main kernel: (guest)ddddd
May 20 00:00:00 test-main kernel: (root)ccccc
May 20 00:00:00 test-main kernel: (guest)eeeee

このログに対してrootに関する行だけ取り除きたい、といった場合、

vimのコマンドモードでこんな風に入力する.txt
:[範囲]global/検索条件/Exコマンド
といったglobalコマンドを実行。
今回は範囲を「%(ファイル全体)」検索条件を「root」やりたい処理を「d(削除)」
globalは省略でgだけに出来るので(ヘルプ :h :global 参照)、それらを踏まえて
:%g/root/d

とやるとrootの行だけ削除されます。
逆に条件に一致しないというのがやりたければ

条件を反転して実行する.txt
「!」をつけることで反転。rootを含まない行だけ削除したい、といった場合は
:%g!/root/d

のようにします。

7
8
0

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
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?