Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save petergi/ad80877ee5ae63951214b0111d3e6a42 to your computer and use it in GitHub Desktop.
Save petergi/ad80877ee5ae63951214b0111d3e6a42 to your computer and use it in GitHub Desktop.

In (N)Vim, you can perform search and replace operations using the :substitute command. Here are the basic steps and syntax for doing search and replace:

Basic Syntax

The basic command for search and replace in (N)Vim is:

:s/pattern/replacement/
  • :s indicates that you want to substitute.
  • pattern is the text you want to search for.
  • replacement is the text you want to replace it with.
  • The trailing / is used to end the command.

Example

To replace the first occurrence of "foo" with "bar" on the current line, you would use:

:s/foo/bar/

Replace All Occurrences on the Current Line

To replace all occurrences of "foo" with "bar" on the current line, add the g (global) flag:

:s/foo/bar/g

Replace in the Entire File

To perform a search and replace throughout the entire file, add the % before the s:

:%s/foo/bar/g

Confirm Each Replacement

If you want to confirm each replacement, add the c (confirm) flag:

:%s/foo/bar/gc

This will prompt you for confirmation before each replacement.

Case Sensitivity

By default, the search is case-sensitive. To make it case-insensitive, you can add the i flag:

:%s/foo/bar/gi

Additional Flags

  • n: Show the number of occurrences that were made.
  • c: Confirm each substitution.
  • g: Replace all occurrences in the line or file.
  • i: Ignore case in the search.

Summary of Commands

  1. Replace first occurrence in the current line:

    :s/pattern/replacement/
    
  2. Replace all occurrences in the current line:

    :s/pattern/replacement/g
    
  3. Replace all occurrences in the entire file:

    :%s/pattern/replacement/g
    
  4. Confirm each replacement:

    :%s/pattern/replacement/gc
    
  5. Case-insensitive replacement:

    :%s/pattern/replacement/gi
    

Conclusion

These commands should help you effectively perform search and replace operations in (N)Vim. Remember to always back up your files before performing bulk replacements, especially when using the g flag!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment