How do I force a case-insensitive substitution without changing the global ignorecase setting?
Answer
:%s/pattern/replacement/ig
Explanation
The :s substitute command accepts /i and /I flags that override your global ignorecase and smartcase settings for that single substitution, letting you choose case sensitivity on a per-command basis.
How it works
/i— force case-insensitive matching for this substitution, regardless ofignorecase/I— force case-sensitive matching for this substitution, regardless ofignorecase
This is particularly useful when you have set ignorecase or set smartcase in your vimrc but need predictable case behaviour for a specific replacement.
Example
Given the file contents:
hello Hello HELLO
With set noignorecase (the default), the following replaces all occurrences regardless of case:
:%s/hello/world/ig
Result:
world world world
Conversely, if you have set ignorecase but need an exact-case match:
:%s/Hello/World/Ig
Result (only the exact Hello is replaced):
hello World HELLO
Tips
- Combine with
gfor global replacement across the whole line, e.g.:%s/pat/rep/ig - These flags also work in range substitutions:
:'<,'>s/pat/rep/ig - To make case-insensitive searching the default, add
set ignorecase smartcaseto your vimrc instead of using/ievery time