Search and replace in Vim: :s and :%s
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:
| Command | Replaces |
|---|---|
:s/old/new/ | the first match on this line |
:s/old/new/g | every match on this line |
:%s/old/new/g | every match in the file (% means every line) |
:5,12s/old/new/g | every match on lines 5 to 12 |
:%s/old/new/gc | every 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.
Your task
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.
- Every address starts with https:// (not done yet)
- user is customer, but only as a whole word (not done yet)
- Nothing else changed, saved and closed (not done yet)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
:s- :s/old/new/ replaces the first old on the line; add g for every one on the line
:%s- :%s/old/new/g replaces in every line of the file; add c to confirm each one
vim \< \>- Word edges in a search: \<user\> matches user but not username More on vim
Every everyday command on one page: the Linux commands cheat sheet.