I often have text in columns and need to replace some things without clobbering similar stuff on the same line... a simple example follows:
Suppose I have highlighted the text in grey with vim visual block mode, and want to replace 80
with 81
; however, I only want replacements within the highlighted visual block.
I have already tried Cntlv : s/80/81/g
; however, that replaces text inside and outside the visual block. (based on Randy's feedback, it's because : s
is a line-wise command).
I know I could use a line-wise visual block replace in this particular instance ( Shiftv : s/80\.1/81.1/g
); however, I'm trying to find a general solution for the problem of having no easy means to replace within a non line-wise visual block (isn't this the kind problem that visual block mode is supposed to help solve?). Answers requiring confirmation like : s/80/81/gc
, are not what I am looking for.
I will restate the question for clarity: How can I replace 80
with 81
by using vim's visual block mode highlight?
By pressing ctrl + r in visual mode, you will be prompted to enter text to replace with. Press enter and then confirm each change you agree with y or decline with n .
Press v to begin character-based visual selection, or V to select whole lines, or Ctrl-v or Ctrl-q to select a block. Move the cursor to the end of the text to be cut/copied. While selecting text, you can perform searches and other advanced movement.
To enable the Visual block mode in Vim, you have to try out the “Ctrl+V” command within the normal mode. You can see that the new. txt file has been opened in the Visual Block mode.
When you press * ( Shift + 8 ) in Normal mode, Vim will search for the word (i.e. keyword ) under the cursor. Assuming the text you want to search is a single word, this is a great way to search.
You need to add \%V
to your pattern. From :help \%V
:
Match inside the Visual area. When Visual mode has already been stopped match in the area that gv would reselect. This is a /zero-width match. To make sure the whole pattern is inside the Visual area put it at the start and end of the pattern.
OP EDIT: the explicit solution is to to use : s/\%V8\%V0/81/g
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