0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vimの置換時のエスケープ処理

0
Last updated at Posted at 2025-12-06

Vimで特殊文字を含む文字列を置換する

// これを
set path+=$HOME/.hoge/fuga/vim
// こうしたい
set path+=$HOME/.cache/vim

こんな時、hoge/fuga -> cacheと置換してあげたいわけですが、特殊文字はエスケープが必要です。
エスケープは\で行えます。
ちなみにエスケープが必要な特殊文字は ^$.*[]/~\ あたりです。

Vimの置換は

:%s/{置換対象の文字列}/{置換後の文字列}/

というコマンドなので、先ほどの例では

:%s/hoge\/fuga/cache/

としてあげれば良いです。

おまけ

1行に複数の置換対象があるとき

先ほど紹介した通常の置換コマンド

:%s/{置換対象の文字列}/{置換後の文字列}/

では1行に複数の置換対象があるとき、先頭の1つしか置換されません。

置換をしたいときは全ての対象文字列を置換したいことが多いと思いますが、そんな時は

:%s/{置換対象の文字列}/{置換後の文字列}/g

とすると全ての対象文字列に対して置換をしてくれます。

置換の確認がほしいとき

また、

:%s/{置換対象の文字列}/{置換後の文字列}/c

とすると置換ごとに実行するかどうかを聞いてくれるようになります。

これらを組み合わせて

:%s/{置換対象の文字列}/{置換後の文字列}/gc

とすることで全ての対象箇所を確認ありで置換することができます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?