Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace only part of a single line in Vim

Tags:

vim

Most substitution commands in vim perform an action on a full line or a set of lines, but I would like to only do this on part of a line (either from the cursor to end of the line or between set marks).

example

this_is_a_sentence_that_has_underscores = this_is_a_sentence_that_should_not_have_underscores

into

this_is_a_sentence_that_has_underscores = this is a sentence that should not have underscores

This task is very easy to do for the whole line :s/_/ /g, but seems to be much more difficult to only perform the replacement for anything after the =.

Can :substitution perform an action on half of a line?

like image 941
Scott Avatar asked Jan 04 '16 20:01

Scott


1 Answers

Two solutions I can think of.

Option one, use the before/after column match atoms \%>123c and \%<456c.

In your example, the following command substitutes underscores only in the second word, between columns 42 and 94:

:s/\%>42c_\%<94c/ /g

Option two, use the Visual area match atom \%V.

In your example, Visual-select the second long word, leave Visual mode, then execute the following substitution:

:s/\%V_/ /g

These regular expression atoms are documented at :h /\%c and :h /\%V respectively.

like image 190
glts Avatar answered Nov 20 '22 22:11

glts