(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:
- Miscellaneous Vim Stuff
- Vertical Columns in Vim (“visual blocks”)
- Navigating files, lines, blocks
- Searching in Vim
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
- For a more permanent solution which means you can clear it by hitting Esc, see here: https://stackoverflow.com/questions/657447/vim-clear-last-search-highlighting
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)
- See solution here, which I have in both my vim configs: https://github.com/nelstrom/vim-visual-star-search/blob/master/plugin/visual-star-search.vim
- To use it, hit v to get in visual mode, highlight the text you want to search for, then hit *
One thought on “Searching and search / replace in Vim”