Learn Practice Daily golf Reference

How to find and replace in Vim

Type :%s/old/new/g and press ↵ to replace every old with new in the whole file. Add c after the g to be asked at each match.

Try it here

Rename qty to quantity

Every qty in the file becomes quantity, with one command: :%s/qty/quantity/g and ↵.

Replace every qty with quantity
1const qty = order.qtyquantity = order.quantity;
1const price = order.price;
2const total = price * qty;
3log(`total for ${qty}: ${total}`);
NORMALLoading the editor…0.0s1:1

This editor needs a keyboard. Read on, and play it at your computer.

TypeReplaces
:s/old/new/ ↵the first old on the current line
:s/old/new/g ↵every old on the current line
:%s/old/new/g ↵every old in the file (% means every line)
:%s/old/new/gc ↵every old in the file, asking at each: y yes, n no, a all the rest, q stop
:%s/old/new/gi ↵every old, Old or OLD: i ignores case
:5,12s/old/new/g ↵only on lines 5 to 12
:'<,'>s/old/new/g ↵only in the lines you selected (press : in Visual mode and Vim types the range for you)
:%s/\<old\>/new/g ↵only the whole word old, not bold or older
:%s/old//g ↵deletes every old (an empty replacement)
Before
let id = 1;
const idx = id + 1;
const ids = [id, idx];
:%s/\<id\>/userId/g↵
let userId = 1;
const idx = userId + 1;
const ids = [userId, idx];
With \< and \> only the word id changes; idx and ids are left alone

Slashes, ampersands and new lines

The slashes are separators, so a slash in your text would end the pattern early. Use another separator instead: :%s#/usr/local#/opt#g works the same way with #.

Two characters are special in the replacement. & stands for whatever matched, so :%s/TODO/[&]/g turns TODO into [TODO]; write \& for a literal ampersand. And \r inserts a line break (\n would insert a null character).

Choosing each match by eye: * and cgn

When you want to look at every match before changing it, there's a way without the command line. Put the cursor on the word and press * to search for it, then cgn to change the next match and type the new word, Esc, and from then on . changes the next one and n skips one. It's the confirm flag, done with two keys per match.