Opening file with vi:
To open file in vi vi [file-name]
command is used. If there is already a file with the name entered, this command will open that existing file otherwise a new file will be created and opened in vi editor.
By running the command vi new.txt
this empty buffer will be opened.
In vi text editor, there are two modes:
Command Mode:
This is the default mode when you open vi. In this mode, you can navigate through the file, delete text, copy and paste text, search, and perform other editing tasks using single-letter commands.
Insert Mode:
In this mode, you can actually insert and edit text. You can enter Insert Mode from Command Mode by pressing the "i" key, and you can exit Insert Mode and return to Command Mode by pressing the "Esc" key.
Navigation in vi Text Editor:
h: Move cursor left.
j: Move cursor down.
k: Move cursor up.
l: Move cursor right.
w: Move cursor forward one word.
b: Move cursor backward one word.
o: Create a new line after the line where cursor is placed and move the cursor to the beginning of that new line.
$: Move cursor to the end of the line.
^: Move cursor to the beginning of the line.
G: Move cursor to the last line of the file.
gg: Move cursor to the beginning of the file.
[line-number]G: Move cursor to a specific line number. e.g.
2G
: Move cursor to line 2.
Editing in vi Text Editor:
x: Delete character under the cursor.
dd: Delete current line.
dw: Delete current word.
yy: Copy current line.
p: Paste copied or deleted text after the cursor.
P: Paste copied or deleted text before the cursor.
u: Undo last change.
. : Redo last change.
D: Delete whole line after the cursor.
[number-of-lines]dd: Delete n number of lines after the cursor. e.g.
2dw
: Delete two lines after the cursor.[number-of-words]dw: Delete n number of words after the cursor. e.g.
2dw
: Delete two words after the cursor.
Search and Replace in vi Text Editor:
/[pattern]: Search forward for a pattern
?[pattern]: Search backward for a pattern
n: Repeat last search in the same direction
N: Repeat last search in the opposite direction
:s/[pattern]/[replacement] : Replace the first occurrence of pattern with replacement in the current line
:%s/[pattern]/[replacement]/g : Replace all occurrences of pattern with replacement in the entire file
Saving and Quitting in vi Text Editor:
:w : Save changes (write)
:q : Quit vi
:q! : Quit vi without saving changes (force quit)
:wq or ZZ : Save changes and quit