Search and replace in a range of line and column
Asked Answered
F

4

6

I want to apply a search and replace regular expression pattern that work only in a given range of line and column on a text file like this :

AAABBBFFFFBBBAAABBB
AAABBBFFFFBBBAAABBB
GGGBBBFFFFBHHAAABBB

For example i want to replace BBB with YYY in line range 1 to 2 and from column 4 to 6, then obtaining this output :

AAAYYYFFFFBBBAAABBB
AAAYYYFFFFBBBAAABBB
GGGBBBFFFFBHHAAABBB

Is there a way to do it with Vim ?

Farias answered 2/10, 2010 at 18:29 Comment(0)
A
12
:1,2 s/\%3cBBB/YYY/

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

Ankara answered 2/10, 2010 at 18:38 Comment(1)
The column is the fourth : :1,2s/\%4cBBB/YYY/Farias
R
4

If this is always the first one you want to replace, simply don't specify /g

:1,2s/BBB/YYY/

would work fine.

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

Replacing the second set of B's on lines 1 and 2 could be done with:

:1,2s/\%11vBBB/YYY/
Rhnegative answered 2/10, 2010 at 18:33 Comment(1)
\%v vs \%c… up to him to tell us.Ankara
L
0

Specifying rows and columns :1,2s/\%>3c\%<7cB/Y/gc

Leprosy answered 26/2 at 19:0 Comment(0)
B
0

Also works:

:%s/\%>3c\%<7c\%>0l\%<3lB/Y/g

c for columns and l for lines or rows

Bondsman answered 17/3 at 1:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.