Vim is an improved adaptation of Vi - the standard Unix visual text editor. Vim is available on literally all Unix-like systems, including Linux and Mac OS.
Vim is quite fast and almost all functions have shortcut keys. Vim is a very useful text editor for programming/scripting and editing configuration files and more.
In this tutorial, we learn how to open a file in Vim / Vi then save and exit the editor.
Vi / VIM open a file
To open an existing file with Vim / Vi, run the command in your terminal:
$ vim myfile.txt
In case the filename doesn't exist, it opens the editor for the new file.
Once the file is opened, the bottom line of the editor shows filename, the total number of lines, and the total size of the file.
Note: If the existing file is not in the current working directory, you should include the file path. For example:
$ vim /home/bob/filename
Vi / Vim edit mode
Vim has two modes that allow you to perform different sets of operations. They are: Normal mode and Insert mode (or called edit mode).
When you open Vim, you are in normal mode. This mode allows you to enter Vim commands and move around the file.
The Vim insert mode allows you to insert text into the editor. To switch from normal mode to insert mode, press i on your keyboard. Notice the -- INSERT -- cue at the bottom left of Vim.
vi / Vim save file
Now, go ahead and enter some text into the editor.
To save your file, you would need to first switch back to normal mode. Press the ESC key to leave the insert mode and return to normal mode.
Next, type :w and press enter to save your file. You can think of this as writing your changes to disk.
You should see a message at the bottom of Vim indicating that your changes have been written.
Note: If you are working on a new file, you would be required to name your file. Below is an example.
vi / VIM save and exit
Further, it is possible to save your file and exit Vim in one go as follows.
Alternatively, run the command following command to quickly save and exit from Vim.
Vi / Vim exit without saving
To quit Vim without saving your changes, the command you should run is;
While in normal mode, enter the following command to close Vim / Vi. This allows you to quit vim if no changes were made to the file.
Quick Overview of Vim / Vi Commands
|1||Open File||Type |
|2||Edit File||Press |
|3||Save File||Press ESC and type |
|4||Save and exit||Press ESC and type |
|5||Quick save and exit||Press ESC and type |
|6||To Quit Without Saving||Press ESC and type |
|7||To Quit (if no changes made)||Press ESC and type |
Here we learned how to open a file in Vim / Vi, as well as how to save and exit from the file.
There are a lot more vi editor command exits but the above command should be good to get started.