Say I have the following line:
|add_test() (| == cursor position)
And want to replace the 'add' with a 'del'.
del|_test()
I can either press X three times and then press i to insert and type del. What I want is something like 3c or 3r to overwrite just 3 characters. Both of these don't do what I want, 3c overwrites 3 characters with the same character, 3r does several other things.
Is there an easy way to do this without manually Xing and inserting the text?
Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.
Change and repeat Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.
To get a newline, use \r . When searching for a newline, you'd still use \n , however. This asymmetry is due to the fact that \n and \r do slightly different things: \n matches an end of line (newline), whereas \r matches a carriage return.
vi positions the cursor at the next occurrence of the string. For example, to find the string “meta,” type /meta followed by Return. Type n to go to the next occurrence of the string. Type N to go to the previous occurrence.
3s
, "substitute 3 characters" is the same as c3l
. 3cl
and c3l
should be the same, I don't know why you'd see the same character repeated. I'm also a fan of using t
, e.g. ct_
as another poster mentioned, then I don't have to count characters and can just type "del".
I struggled with the "replace a couple of characters" for a few days too; 'r' was great for single characters, R
was great for a string of matching length, but I wanted something like the OP is asking for. So, I typed :help x
and read for a while, it turns out that the description of s
and S
are just a couple of pages down from x
.
In other words, :help
is your friend. Read and learn.
Use c{motion} command:
The word is determined by iskeyword variable. Check it with :set iskeyword? and remove any '_', like that :set iskeyword=@,48-57,192-255. By the way see :help c and :help motion if you want more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With