Friday, June 14, 2024
HomeLinux CommandsHow to edit/modify files with Vim and Vi command

How to edit/modify files with Vim and Vi command

What is Vim?

Vim/Vi used to edit or modify a text files in CLI (Command Line Interface). It is most popular and people’s choice text editor in Linux. We gonna discuss its usage and option.

Most often Vim is started to edit a single file with the following command. Vim is nothing but improved version of vi command. We can also use vi command for same purpose. You can use according to your choice.

vim file

If you specify an existing file, then the editor open it for you to edit. Otherwise, you can create a new one.

vim [file_new] or [file_existing]

Vim or Vi has two Modes:

Insert mode press i to insert. We can insert/add text in the file using insert mode.
Command mode for operations the like saving, exiting from a file etc .

I am gonna use test1.txt file for vim command also you can edit any file. Run following command and you gonna get into normal mode.

vim test1.txt

Now if you want to edit your file, you need to go on insert mode. Press “i” for insert mode and now you can add text in the file. It is especially useful for editing programs.

After adding your text, Press “escape” key to switch back to normal mode.
Now save and exit file by typing : x OR :wq and press “enter” key.

You can play around with the arrow keys by using the vim movement keys, as follows.

  • h left
  • j down
  • k up
  • l right

Vim commands for Escape/Normal mode.

  • :w save changes to file.
  • :wq save and exit from file.
  • : x save and exit from file.
  • :q! Exit without saving.
  • i is used to insert.
  • o cursor will move to next line to insert.
  • x Delete the character the cursor is on.
  • yy Copy current line.
  • Ctrl+b Go back one page.
  • Ctrl+f Go forward one page.
  • p past copied line or text.
  • y4 Copy multiple lines. 4 is the number of lines we want to copy.
  • /stringname to search desired text. String name is the text we want to search.
  • n go to next searched string.
  • shft+n go to previous searched string.
  • :%s/oldstring/newstring/g Replace old text with new text.
  • :9 to go line no. 9
  • Shift+x Delete the character before the cursor.
  • dd Delete the current line, also used for delete.
  • Shift+d Delete everything from the cursor to the end of the line.
  • u Undo a line you just deleted.
  • Shift+u Undo all changes to the current line.
  • gg To go on the top of file.
  • shft+g To go to the end of file.

That’s about it.You can get a handful of experience on vim by using above commands.



Please enter your comment!
Please enter your name here

Most Popular