Searching and search / replace in Vim

(Note that this was written after I spent a few months learning Vim. If you’re just stuck in Vim and want to get out, see What to do when you get stuck in a Vim editor).

I’m publishing my notes on the things that are useful in Vim but that I keep forgetting. My notes are split into four sections, so I’ll publish four posts:

This is the fourth post, and it’s about searching  and search / replace in Vim.

Search for term in file

  • Like this: /[search term – regex]
  • Type n to get next search result
  • Type N to get previous search result
  • For case insensitive search, add \c to the command (either at start or end)
  • If you then get highlighting which won’t go away, type :noh

Search and replace

  • Like this: :%s/[search term]/[replacement]/g
    • %s means whole file, /g means every occurrence on every line
    • If you want it to ask you for confirmation on every replacement, add c as well: :%s/foo/bar/gc
    • More here: https://vim.fandom.com/wiki/Search_and_replace
    • And here: https://www.linux.com/learn/vim-tips-basics-search-and-replace
    • If your strings contain forward slashes, then you can replace the forward slashes in the command with any other character!
    • For case insensitive search, add \c to the command (either at start or end)
    • To do it on whole words only: :%s/\<word\>/newword/g – you have to delimit the word with \< and \>

Find character on this line

  • f – find character on this line
    • Add a number to do multiple
    • Eg 2f_ will find the second underscore character on this line

Find the word under the cursor

  • This: *
    • This works on words containing underscores
    • By default it won’t work on words containing hyphens
      • You can change this by adding set iskeyword+=- to .vimrc
      • Or just type :set isk+=- in Vim

Find whatever text you have highlighted (in visual mode)

One thought on “Searching and search / replace in Vim

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.