Skip to content

Search and replace in Vim: :s and :%s

AdvancedLesson 40 of 668 min

Replace text in Vim with :s and :%s, add g for every match and c to confirm each one, match whole words with \< \>, and change slashes without a mess.

The shop is moving to HTTPS, and every http:// address in site.conf has to change. Doing it with cw and . works, but for "every one in the file", Vim has a command: substitute.

vim site.conf

:s

:s/old/new/ replaces the first old on the current line. Flags at the end change that:

CommandReplaces
:s/old/new/the first match on this line
:s/old/new/gevery match on this line
:%s/old/new/gevery match in the file (% means every line)
:5,12s/old/new/gevery match on lines 5 to 12
:%s/old/new/gcevery match, asking first: y yes, n no, a all, q stop

u undoes a whole substitute in one go, so it's safe to try.

Slashes in the text

The / separates the parts, so a / in the text needs a backslash: :%s/http:\/\//https:\/\//g. That's hard to read. Any other character can separate the parts instead, and # is a common choice:

:%s#http://#https://#g

Whole words only

:%s/user/customer/g would also turn username into customername and superuser into supercustomer. \< and \> mark the edges of a word, so \<user\> matches user on its own and nothing longer:

:%s/\<user\>/customer/g

The c flag is the other safe way: it shows each match and lets you say yes or no.

Searching first

/\<user\> with Enter highlights the matches before you change anything, and :%s//customer/g (an empty pattern) reuses your last search.

Your turn

In site.conf: (1) change every http:// to https://; (2) change the word user to customer wherever it is a whole word, leaving superuser, username_field and max_users alone. Save and quit.

Next