Working with Vim

Working with Vim

Vim is a very popular text editor in Linux-based Operating systems. It is quite easy and efficient to use. Let's see how we can work around text files using Vim.

Creating File

We can create a file using Vim by typing the following command in the terminal.

Where "demo.txt" is a file name. If the file "demo.txt" already exists vim will open it, if not vim will create the file "demo.txt" and then open it.

Modes in Vim

1. Command Mode

Command mode is the default mode of Vim. We can not edit the text in this mode. It only supports the execution of commands.

Following are a few useful commands:

  1. i - It changes the mode of vim from default command mode to insert mode.

Now we can add some text to our file.

  1. escape + :wq - It is used to quit vim after saving the file to disk.

  2. escape + :q! - It quits the vim editor without saving the changes made in the file.

  3. dd - It deletes a line in the text file on which the cursor points.

    After entering the second d the 4th line will get deleted.

  1. dn - It will delete the current line where the cursor is pointing and the "n" lines below it.

    Let's try "d2".

    After that first line where the cursor was pointing and 2 lines below it will get deleted.

  2. u - It undoes the result of the previous result.

    After using "u" command we will get back the deleted content of our text file.

  3. 0 - Zero is used to point the cursor to the start of a line.

    After using "0" the cursor will point to the beginning of the line.

  4. $ - It is used to point the cursor to the end of a line.

    After using "$" the cursor will point to the end of the line.

  5. A - It is used to jump to the end of the line and change mode to insert mode.

After using "A" mode will get changed to "insert" and the cursor will point to the end of the first line.

  1. nG - It will move the cursor to the start of "nth" line.

Let's try "4G" here.

  1. /pattern - It will move the cursor to point at the first occurrence of the pattern.

    Let's find "learn" in our text file.

2. Insert Mode

Insert mode is the mode in which you can enter the text file. We can switch between insert mode and command mode using the escape key.