brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: :%s//new/g in Vim replaces whatever you searched for last

Vim
~/tips/tip-vim-substitute-empty-pattern-last-search

/oldname

An empty pattern in a substitute command reuses your last search, so you can look first and replace after.

A safe way to rename something in Vim is to search for it first and look at the matches. Then you have to type the same pattern again in the substitute command. You don’t have to.

/oldname
:%s//newname/g

When the pattern part of :s is empty, Vim uses the last search pattern. Search with /oldname, press n a few times to check that the hits are the ones you meant, then run :%s//newname/g. The same pattern is used, including a long regular expression you would hate to retype.

It also works with a search you started with *. Put the cursor on a variable, press *, and then :%s//newname/g renames it in the whole file. Add the c flag, as in :%s//newname/gc, if you want Vim to ask before each change.

One caveat from :help last-pattern: Vim remembers two patterns, one for searches and one for :s and :g. An empty pattern takes the one used most recently, so if you ran another :s command after your search, that one wins. When the replacement hits the wrong thing, press u to undo and search again right before you substitute.

Further reading: Vim help: pattern, last-pattern, Vim help: change, :s_r

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Vim tips :%s/<Ctrl-r><Ctrl-w>/newname/g find . -name "*.conf" | vim – vim --clean file.txt :set textwidth=72 :mksession All Vim tips (45) All topics

Link