How to use vi editor?
Linux peoples commonly use vi editor. vi/vim editor is a command line editor. Vim is a text editor that is upwards compatible to Vi. It can be used to edit all kinds of plain text. It is especially useful for editing programs.
Starting vi/vim
# vi filename edit a file named "filename"
# vi newfile create a new file named "newfile"
ENTERING TEXT
i insert text left of cursor
a append text right of cursor
MOVING THE CURSOR
h left one space
j down one line
k up one line
l right one space
BASIC EDITING
x delete character
nx delete n characters
X delete character before cursor
dw delete word
ndw delete n words
dd delete line
ndd delete n lines
D delete characters from cursor to end of line
r replace character under cursor
cw replace a word ncw replace n words
C change text from cursor to end of line
o insert blank line below cursor (ready for insertion)
O nsert blank line above cursor (ready for insertion)
J join succeeding line to current cursor line
nJ join n succeeding lines to current cursor line
u undo last change
U restore current linep paste copy line5yy copy five line
MOVING AROUND IN A FILE
w forward word by word
b backward word by word
$ to end of line
0 to beginning of line
H to top line of screen
M to middle line of screen
L to last line of screen
G to last line of file
1G to first line of file
<Control>f scroll forward one screen
<Control>b scroll backward one screen
<Control>d scroll down one-half screen
<Control>u scroll up one-half screen
n repeat last search in same direction
N repeat last search in opposite direction
CLOSING AND SAVING A FILE
ZZ save file and then quit
:w save file
:q! discard changes and quit file
SEARCHING and REPLACING
The formal syntax for searching is:
:s/string
The syntax for replacing one string with another string in the current line is
:s/pattern/replace/
Here “pattern” represents the old string and “replace” represents the new string.
The syntax for replacing occurrence of a string in the text is similar. The only difference is the addition of a “%” in front of the “s”:
:%s/pattern/replace/:%s/http:\/\/localhost/http:\/\/devopsfunda.com
To undo recent changes, from normal mode use the undo command:
u undo last change (can be repeated to undo preceding commands)
Ctrl-R Redo changes which were undone (undo the undos). Compare to . to a previous change, at the current cursor position. Ctrl-R (hold down Ctrl and press r) will redo a previously undone change, wherever the change occurred.