Example of a vi script
Vi editor allows the user to create and execute custom scripts to perform and automate various tasks. Here is a simple vi script that replaces all the occurrences of “oldword” with “newword” in a file.
vi replace_script.vi
In the replace_script.vi file write the following command to replace the occurrences of a word in the file,
:%s/oldword/newword/g
Press Esc to exit insert mode and write :wq command to save and exit.
Now to apply this script to a file use the following command,
vi -s replace_script.vim yourfile.txt
Replace [yourfile] with the name of the file you want to apply the script.
Create/Edit a file in the vi editor
To Create/Edit a file using Vi editor you have to run the below command in the terminal, it will open a file to edit if it exists otherwise it will create a new file.
Syntax:
vi filename
Replace [filename] with the name of the file you want to create or edit. In this case, the filename is GFG_Temp/vi_delete.txt
Basic Navigation in editor
To navigate within the file, vi editor provides some commands which are as follows:
Command |
Description |
---|---|
k |
Moves the cursor up one line. |
j |
Moves the cursor down one line. |
h |
Moves the cursor to the left one-character position. |
l |
Moves the cursor to the right one-character position. |
Saving the changes and quitting the editor
To save the changes in file and quit the vi editor follow the below steps:
- If you are in insert mode then press Esc to enter in command mode
- To save the changes to file write :w in command mode and press Enter
- To quit the file write :q in command mode and press Enter
- To save and quit the editor in a single command use :wq to combine the effects of save and quit and press Enter
Is vi editor free?
Yes ! vi is a free and open-source text editor. Vi editor was developed in 1976 by Bill Joy, vi editor is a widely used text editor in Unix/Linux systems and is known for its efficiency and flexibility. An improved version of Vi editor was released later in 1991, popularly known as VI IMproved (VIM).