Important Vim lessons that nobody tough me 😮‍💨

Learn how to search and replace in Vim

Important Vim lessons that nobody tough me 😮‍💨
Photo by Adrian Dascal / Unsplash

Vim is awesome text editor, but It requires from you to change your mind to a new form of workflow.

This is part of a series of posts where I will share those lessons that nobody else tough me and I learned through the time and are part of Vim's identity.

TL;DR

Important vim lesson:

  • How to search/search and replace.

Use Vim's search 🔍 by pressing / in normal mode.

Use Vim's search and replace 🎯 by typing :s/text-to-search/text-to-replace and hitting enter

How to search in Vim 🧐

Vim doesn't offer a friendly UI as any other text editor, and it is evident to you when you face the first basic challenge of search for something.

How to do it? Here in Vim you will not to have Ctrl + f as option, instead you will find a new way by pressing just / in normal mode, and follow that you shouldn't not notice nothing different in Vim just at the bottom left corner you will see that appears a / follow that by typing the text you are looking for and voila, the cursor will jump to the first match.

  • How jump to the next coincidence ? just hits n
  • How to jump to the previous one? Just hits N (capital)

Slash / mades a forward ⏩ search, while question ❓ mark does a backward search .

Now let's to replace something 🧩

Now you know how to search, let's to replace by typing  `:%s/whatever/new stuff` if you hits Enter you will have did a replace of whatever by new stuff.e

Let's to desglose this command:

'%' means the whole document.

's' means substitute.

'/' will be followed by the target search.

'/' and second slash will be followed by the replace string.

Some advance replace commands 🥸

after last slah you could add more parameters like:

'i' for ignore case.

'g' for global replace (replace all coincidences in the same line, otherwise will only first match be replaced)

'c' to confirm each replace before be replaced, it will land you into more commands you will see on command mode:

  • 'y' to accept
  • 'n' to skip and go for next match
  • 'a' to replace all matches
  • 'q' to quit.

So a common command you will use regularly could be:

':%s/target/new/gic'

Above command will replace all "target" text by "new" and it will replace all matches at same line, ignoring the case and asking you to confirm each relace by separate.

conclusion 🙌

Vim search and replace is a really simplies tool really useful in your daily workflow, and the best of all is that it follows UNIX kind of standards to search and replace text, so you could apply your knowledge in command line tools like 'sed' to find and replace text into several files, really useful to write scripts to deploy a site in your CI environment.