How to create a file in vim editor and save/exit the editor

Vim editor in Linux

Vim(Vi IMproved) is a widely used text editor in Linux. It is a enhanced version of vi editor. In Windows/Mac operating system, we are using text editors such as Notepad, Sublime Text and Atom. Similarly Linux has the vim text editor to create or edit the text file.

Modes in vim editor

There are three modes in vim editor.

  • Command mode – This is the default mode and all our keys are commands (like find,replace,quit, etc). When we press Esc key, it goes back to this mode if we are in other modes.
  • Insert mode – When we press i key, it enter into insert mode where we need to type the text to save/modify in the file.
  • Visual mode – It used to select/high light the string in the editor. It has two types such as visual block and visual line.
    • visual block – The short cut key is Ctrl+v. This is useful for vertical changes.
    • visual line – The short cut key is v. After pressing v key, we can use arrow keys to high light the lines in the file.

Create file in Vim editor

In the Linux command line, we just need to type the vim followed by file name and press enter to invoke the vim editor

Create file in vim editor
Create file in vim editor

As we can see in the above image, It opened the vim editor and showing the file name as sample at the end.

Edit/Change file in vim editor

Now we are pressing the key i in the vim editor. It will enter into insert mode where we can type the text in the file.

Insert mode in vim editor
Insert text in vim editor

As we can see in the above image, the insert mode enabled in the vim editor. Lets type the few lines in the file. Press enter to go to next line and continue typing your text.

insert lines in vim editor
Type lines in vim editor

We have entered three lines as above in the Sample file using vim editor. Now its time to save the file.

Save/Exit the file in vim editor

We need to follow the below steps to save and exit the file.

  • Press Esc key to go back to command mode. Once it is done, the string — INSERT—- will be disappeared at the bottom of the editor.
  • Type :wq to write file and quit the editor
  • Press Enter key to execute the command.
Save and exit the file in vim editor
Save and exit the file in vim editor

Now the file got saved with all the lines that we entered in the vim editor. Similarly you can follow the same steps to modify the existing files.

Please note that the command :x is also used to write the file and quit the vim editor. But it write the file only if it has been modified whereas the command :wq always write the file and change the file modification time even if the file was not changed.