2024-12-19
Before diving into text manipulation, efficient navigation is key. Vim’s modal nature (Normal, Insert, Visual) dictates how you interact with the text.
i
(insert before cursor), a
(insert after cursor), o
(open a new line below), O
(open a new line above).Esc
key.h
: Leftj
: Downk
: Upl
: Rightw
: Next wordb
: Previous worde
: End of word0
: Beginning of line$
: End of linegg
: Go to the beginning of the fileG
: Go to the end of the filenG
: Go to line nExample:
Let’s say you have a file named my_text.txt
with the following content:
This is a sample text file.
It contains multiple lines of text.
We will use vim to edit it.
Open the file in Vim: vim my_text.txt
Navigate to the beginning of the file using gg
, then move to the end of the third line using 3j$
.
Vim offers a rich set of commands for editing text.
x
: Delete character under cursordw
: Delete worddd
: Delete lined$
: Delete to end of linedgg
: Delete from cursor to beginning of filedG
: Delete from cursor to end of fileyw
: Yank wordyy
: Yank liney$
: Yank to end of linep
: Paste after cursorP
: Paste before cursorcw
: Change wordcc
: Change linec$
: Change to end of lineExample:
Continuing with my_text.txt
, let’s make some changes:
2gg
).dw
.iincludes<Esc>
.3j$
).a efficiently<Esc>
.Vim provides powerful search and replace functionalities.
/pattern
searches forward, ?pattern
searches backward. n
repeats the last search forward, N
repeats the last search backward.:s/old/new/g
replaces all occurrences of “old” with “new” on the current line. :1,$s/old/new/g
replaces all occurrences of “old” with “new” in the entire file. :s/old/new/gc
prompts for confirmation before each replacement.Example:
Let’s replace all instances of “text” with “data” in my_text.txt
:
:1,$s/text/data/g
This command will replace all occurrences of “text” with “data” throughout the file.
Vim allows you to efficiently work with multiple files.
vim file1.txt file2.txt
:n
(next file), :N
(previous file)Visual mode allows for selecting blocks of text for various operations.
v
(character-wise), V
(line-wise), Ctrl-v
(block-wise)d
deletes the selected text, y
yanks it, and c
changes it.Example:
Select a block of text in visual mode and then use d
to delete it, or y
to copy it.
This only scratches the surface. Vim offers many more commands for advanced operations like macros, regular expressions, plugins, and more. Exploring these features unlocks even greater productivity.