Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim search and replace limited to the highlight in visual block mode

I often have text in columns and need to replace some things without clobbering similar stuff on the same line... a simple example follows:

vim visual block-mode screenshot

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?

like image 767
Mike Pennington Avatar asked Jun 03 '11 17:06

Mike Pennington


People also ask

How do I highlight and replace in Vim?

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 .

How do you highlight a block of text in Vim?

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.

How do I use visual block mode in Vim?

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.

How do I search for a selection in Vim?

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.


1 Answers

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

like image 50
Randy Morris Avatar answered Sep 30 '22 07:09

Randy Morris