vi Global Search and Replace

This is a quick article to show you what is in my opinion, the  easiest way to perform a global search and replace in vi. This post assumes you already have a basic understanding of vi.

While vi is a full screen editor, it’s foundation, is still based on a line editor.

Let’s say  that you have to perform a global search for the word align and replace it with the word alignment. A very simple task which in a modern editor is a no-brainier, while in vi, it requires a little knowledge.

Now, let’s actually perform the search and replace. In order to do that in vi, you have to prepare your screen to accept command by typing “:“, then tell what line to start, and what line to end, to then actually perform the command, which in this case is a search and replace command. Following is the complete command to perform the search and replace:

:1,$s/align/alignment/g

Now, let’s describe exactly what each sub-command is doing:

  • 1 is simply telling vi to start from line 1
  • $ is telling vi to select until the end  of file
  • s is for searching
  • /align/ searches for  the align word
  • /alignment/ simply replaces align with alignment
  • /g means to replace should it find more than one instance on one line

Try the command for yourself and see the results.

Thank you for checking my site out…

Leave a Reply