4

Consider this string:

1 1 1

When I mark the first two 1s in visual mode and then :'<,'>s/1/2/g, all 1s on the line are replaced by 2s, not just those in the selected region. Why is this the case and how can I restrict the operation to the selected text?

7

The :s[ubstitue] command operates on whole lines and the [range] prefix is a range of lines.

To restrict the operation to just the visually-selected region, you can use the \%V atom in your search pattern. That is, visually-select the first two 1s in your example, then use this command to replace just those 1s:

'<,'>s/\%V1/2/g

See also

:help /\%V

The :help entry says to put \%V at the start and end of the pattern, but I didn't read that before trying it and it worked in the example here with \%V at just the start of the pattern.

  • Many thanks, @garyjohn. I'm actually using Evil not Vim and found out that the \%V atom is not supported there. Bummer. For those who are interested, the relevant feature request is here. – tmalsburg Jan 19 '16 at 3:06
3

That is, because you have provided only a line-based range for the :s command. There is no way to have an ex command apply to only a column-based selection. Specifically for the :s command there exists the \%V regex atom, that allows to substitute within a selection only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.