Search
StarWind is a hyperconverged (HCI) vendor with focus on Enterprise ROBO, SMB & Edge

The “old new thing” or an introductory guide to Vi

  • April 1, 2021
  • 25 min read
Mikhail is IT engineer focusing on applications and infrastructure support domains. He works closely with K2 platform and Microsoft technology stack and holds number of certifications from these software vendors.
Mikhail is IT engineer focusing on applications and infrastructure support domains. He works closely with K2 platform and Microsoft technology stack and holds number of certifications from these software vendors.

Actually, my plans were to blog about my AWS certification experience or maybe write up something related with containers, but as I recently moved out from 90% Microsoft shop to the space dominated by Unix based systems, I found myself in a situation when my learning needs started to include things extremely remote from a “new and shiny” tools bucket. It is not a secret that Unix like operating systems are powering public and private clouds as well as the most of the modern born in the cloud software, and this, somewhat surprisingly, also means that working with cloud native applications sometimes includes things beyond new and shiny web abstraction layers and agile orchestration and management tools. What I’m talking about? Meet a vi, a text editor from the era of character based serial terminals which is just one of the many time-tested and pervasive tools from Unix like operating systems world.

Why on earth it is still important nowadays? Well, being present on anyUnix based system vi is always available for you to use, and given the fact that we have a cattle service model as a predominant way of managing and servicing our systems, you won’t be installing convenient text editor of your choice on each and every container which provisioned without it, rather you would need to do a quick change with a tool which is always available for you instead of wasting time on fetching out more convenient tool (and sometimes getting that other tool won’t be even possible).

While clear benefit of vi is that it is readily available on all systems, its downside is that it has a somewhat steep learning curve. With no GUI at all, not having even a text-based pseudo-GUI, it can be a bit of a culture shock for average modern user (even for the one who was exposed to some text-based pseudo-GUI applications like Norton Commander and similar things). Quite typical experience for a newbie who starts vi editor for the first time is a reflexive desire to exit out of it which bumps into a problem that even quitting out of vi is a problem if you don’t know how to work with it (if that encounter happens on real physical machine some even ending up doing hard reset to get out of the problematic situation). But let me reassure you, that there is not that much to learn for the most frequent vi use cases like making few small changes to config file(s) for testing purposes or search for something in a log, and there is a method in this madness. More advanced features of vi can be learnt on as needed basis, and most likely they will stay out of scope for majority of people as these days massive configuration files editing and composing supposed to be done with the help of more convenient editors and then those configuration files just get rolled out with some sort of orchestration tool, hence you most likely won’t be using full power of vi just because there is no practical reason for doing that nowadays except for sport if you are into it.

Enough of introductory wording and let me try to cover some history of vi which explains why it is so peculiar in its behavior and further touch on basic commands which allow you to survive and succeed with it.

To better understand vi, we should take into account its origins. Vi history can be traced back to the time of character based terminals, and you still see a legacy of that era using vi/vim today, for example in its use of H, J, K, L letters for left, down, up and right cursor movements which is basically a vestige from the time when these letters were marked with respective arrows on keys of the Lear Siegler Incorporated ADM 3A serial terminal on which vi was originally written. Some other things in vi which look strange by modern standards it also owes to its origins in the world of hardware terminals limited to 12 or 24 lines of 80 characters.

Zoom in on ADM-3A Mint-Blue

Zoom in on ADM-3A Mint-Blue, photo by Chris Jacobs, source – Wikipedia

 

Looking at those terminals images which can be found in abundance in the internet some of you will readily recognize “computers” (or more correctly “dumb terminals”) from post-apocalyptic world of Fallout series, as chances are higher that you saw such type of hardware there than in real life 😊 Software wise vi/vim history traces back to ed text editor which was one of the first parts of the Unix OS developed (see timeline below, although exact dates can be imprecise as a different time points can be counted for a start of existence for each specific program, e.g. we can take a year when the code was first written/initial release or year of initial release under its own name).

Vi editor and its predecessors - historical timeline

vi editor and its predecessors – historical timeline

 

On the end of this evolutionary process is vim which has been ported to a much wider range of OS’s than vi and includes support for popular programming languages (C/C++, Python, Perl, shell, etc.) providing syntax highlighting, code folding, etc. and this is where we are now with vi. According to my observations, on the most of modern Linux distributions (think of Ubuntu or Amazon Linux) you can type in vi or vim and both of those commands will start vim. For simplicity we will be using term/command vi throughout this blogpost.

Now when we get an idea where vi comes from, we can focus on how we can work with it. You can start it by typing vi and hitting enter key in our terminal which will give you splash screen with some useful info to get you started and bunch of ~ signs (see screenshot below). These blue tilde signs represent empty lines, and you will also see those if you run vi specifying non existing file name to create it or when opening existing file which contains less lines of text that number of available lines on your screen.

VIM splash screen

VIM splash screen

But most of the time you will probably nr starting vim to edit some file by typing in vim filename and in such case, you will see something like this:

Vi with sample Python program file opened

Vi with sample Python program file opened

 

When you start vi specifying existing file you will see file contents and not much more – blinking cursor which can be moved up and down with keyboard arrows or K and J keys respectively, but not much more. But don’t panic and focus on the lowest line on the screen – there we have a basic file information, including a file name, encoding and number of lines and characters information. This point is typically when one may start panic as seemingly nothing works and you can neither edit nor quit out of this program. But no worries you just need to realize that vi has two modes and fully controlled through keyboard commands without UI, and with vi we always start in command mode which can be switched to edit mode by pressing i key on a keyboard (use Esc to go back to the command mode) and we can make changes to text only in edit mode (except for deletion of existing text elements which is possible in command mode). As soon as you know that life is getting a bit easier (really 😊) as it is now only a question of knowing some commands and hotkeys – and when it comes to the basic stuff there are just a few of those.

Let’s go through couple of simple examples, starting from making and saving changes into a text. In my case we have a hangman.py Python program file opened with vi hangman.py command (you can practice with any other file you have) and we are now in edit mode, so we can hit i make some changes and then hit Esc to get out of edit mode. When you are in edit or insert mode, you will see word INSERT on the bottom line of vi:

Vi in Edit/Insert Mode

Vi in Edit/Insert Mode

 

Once again, as soon as we made changes/added some text, we can switch back to command mode by pressing Esc or, alternatively, you can hit “:” button on a keyboard which will replace INSERT word in bottom left corner to colon sign and allows us to type commands after it, e.g., w and then Enter for write file or wq to write and quite out of vi. That “:” opens kind of “command prompt” and it is a part of command mode, but sometimes people refer to this mode as a third and separate mode employing “last-line mode” term. But irrespectively of how you name it, colon is kind of your console line which allows you to type in more complex commands and it is what you use for things which go “out of scope” of opened file – saving it to disk, opening another file, switching between multiple opened files (yes vi can do it), all this done through colon and respective commands. Super powerful feature of vi is taking line or other fragment of text and pass it to external Unix command and then get result back into same place, which allows you to pass fragments of your text through such commands as fmt, tr, grep, sed, awk and get results back into your text file without leaving vi (and you can do a lot of things with that). Just as a simplistic example of that you can try move your vi cursor to some line you want to convert/modify and type in the following command: :.!tr a-z A-Z – it will convert current line (which is referred by “.!”) to upper case.

But if we go back to basic examples, basic edit sequence is simple: you open file with vi filename command, activate edit mode with i key and once changes are made you switch back to command mode with Esc and use :wq + Enter or Shift + ZZ to save file and quit out of vi. Deleting lines, or words from the text is possible without entering insert mode – you just use commands for that while in command mode – with cursor on beginning of a word or a line you can press dw or dd to delete word or line respectively, and then save your changes the same way you do after making them in edit mode. Actually, what we already discussed can cover most of your basic text editing needs, but let’s look at how to do find and replace operations before finishing off with examples. To do a find and replace in vi you enter “last-line command” mode by hitting colon while in command mode and type the following command: %s/old_text/new_text/g and then hit Enter – it will replace all occurrences of old_text with new text on all lines of the file. After processing this command vi will display in the bottom left corner that N substitutions were made on N lines (see screenshot below where it says “11 substitutions were made on 11 lines”). Scope of the find and replace operation can be modified to first occurrence or all occurrences within a line or on all lines by adjusting the command.

Find and replace in vi – number of substitutions made displayed in the bottom left corner

Find and replace in vi – number of substitutions made displayed in the bottom left corner

 

I guess examples discussed above cover 80% of most frequent file editing needs with vi, and below you can find a table which lists some useful commands and shortcuts of vi. I deliberately tried to limit the table below to the most frequently used commands, and in case you need more you can try to struggle with vi built-in help or use its online version which may be more convenient to navigate and search. There are also plenty of blogposts, articles, and online courses on vi which can help you to get started or take your vi skills on a next level. In case you have LinkedIn Learning subscription there are “Learning vi” and “Learning Vim” courses available in their library, and you can find many more resources in other places.

Base set of vi commands

Enter and exit vi

vi filename

Start vi from shell and edit existing or new file (multiple file names can be specified so that you can work with them in the same vi session)

:wq + Enter or Shift + ZZ

Save changes and quit

:q! + Enter

Quit without saving changes

Move around (Command Mode)

Keyboard arrows or h, j, k, l

Move cursor around (in command mode)

NG (where N is a number)

Jump to a line N (in command mode), note that you need capital G, commands are case sensitive

Make changes

i

Enter to insert mode

Esc

Exit from insert mode back to command mode

x

Delete one character based on cursor position

dw

Delete current word

d^

Delete from cursor position to the beginning of the line

dd

Delete current line

de

Delete from cursor position to the end of the word

d$ or D

Delete from cursor position to the end of the line

Search and Replace

:s/old_text/new_text/

Replace first occurrence of old_text with new_text on current line

:s/old_text/new_text/g

Replaces every occurrence of old_text with new_text on current line

:%s/old_text/new_text/

Replace first occurrence of old_text with new_text on every line

:%s/old_text/new_text/g

Replace every occurrence of old_text with new_text on every line

Table. Main vi commands

 

This concludes my introductory post on vi and I hope it will help someone to get started with this editor or at least to go past initial frustration stage if not faster than at least with lesser levels of stress. I also noticed that with vi it is frequently love or hate relationship for many users, but I would suggest you staying away from both of these extremes – just learn the basics of vi to have it in your toolbox, it may not be the most advanced and frequently used tool in it, but it is definitely the one you want to have and being able to use for occasional needs. As usual feel free to leave your questions and feedback in the comments section below.

Hey! Found Mikhail’s insights useful? Looking for a cost-effective, high-performance, and easy-to-use hyperconverged platform?
Taras Shved
Taras Shved StarWind HCI Appliance Product Manager
Look no further! StarWind HCI Appliance (HCA) is a plug-and-play solution that combines compute, storage, networking, and virtualization software into a single easy-to-use hyperconverged platform. It's designed to significantly trim your IT costs and save valuable time. Interested in learning more? Book your StarWind HCA demo now to see it in action!