Search and replace in a range of rows and columns

I want to apply a search and replace a regex pattern that only works on a given range of rows and columns in a text file as follows:

AAABBBFFFFBBBAAABBB AAABBBFFFFBBBAAABBB GGGBBBFFFFBHHAAABBB 

For example, I want to replace BBB with YYY in a linear range from 1 to 2 and from column 4 to 6, then get this output:

 AAAYYYFFFFBBBAAABBB AAAYYYFFFFBBBAAABBB GGGBBBFFFFBHHAAABBB 

Is there any way to do this with Vim?

+6
vim regex
source share
2 answers
 :1,2 s/\%3cBBB/YYY/ 

\%3c means the third column (see :help /\%c or more globally :help pattern )

+11
source share

If this is always the first one you want to replace, just do not specify / g

 :1,2s/BBB/YYY/ 

will work fine.

Alternatively, if you need to specify exactly which column you want to replace, you can use the syntax \%Nv , where N is the virtual column (the column is what it looks like, so the tabs are multiple columns, use c instead of v for actual columns )

Replacing the second set B with lines 1 and 2 can be done with:

 :1,2s/\%11vBBB/YYY/ 
+4
source share

All Articles