Wiki

by yszheda

View project onGitHub

Tip 87: Meet the Substitute Command

Return to the top: <<Practical Vim>>

:[range]s[ubstitute]/{pattern}/{string}/[flags]

Tweak the Substitute Command Using Flags

References:

# If you open the file in vim,
# then you can \"ayy@a the next line to execute the vim command: 
:h :s_flags
  • g flag makes the substitute command act globally, causing it to change all matches within a line rather than just changing the first one.
  • n flag suppresses the usual substitute behavior, causing the command to report the number of occurrences that would be affected if we ran the substitute command.
  • e flag silence these errors.
  • & flag simply tells Vim to reuse the same flags from the previous substitute command.

Special Characters for the Replacement String

References:

# If you open the file in vim,
# then you can \"ayy@a the next line to execute the vim command: 
:h sub-replace-special
Symbol Represents
\r Insert a carriage return
\t Insert a tab character
\\ Insert a single backslash
\1 Insert the first submatch
\2 Insert the second submatch (and so on, up to \9)
\0 Insert the entire matched pattern
& Insert the entire matched pattern
~ Use {string} from the previous invocation of :substitute
\={Vim script} Evaluate {Vim script} expression; use result as replacement {string}