1

How can I :substitute, in the current line, a word on which cursor is, but only after the cursor position.

e.g.: when doing (illustratively, may not exact correct command):

:s/<C-r><C-w>

that is user hit : s / Ctrl+R Ctrl+W

it will not substitute the word where cursor is if such word exists before cursor position.

2 Answers 2

0

The substitution command is:

:s/\v(%.c|%>.c)Ctrl+RCtrl+W

Where:

  • \v turn on magic (that makes that special pattern atoms like (, | or % doesn't need to be escaped)
  • \%.c match at the cursor column and
  • \%>.c match after the cursor column

More information with: :help /\%c

But for this use case I would:

  • use * to find the next occurence of the word at the cursor
  • use cw keyboard command to change it
  • use n to find the next occurence
  • use . to repeat the change
  • until the next occurences are changed
  • use N to find the initial occurence
  • use . to repeat the change

Looks complicate to explain but on most of the cases it will probably requires less typing.

5
  • 1
    Ctrl+t . No at all mention on it . Commented Jun 12 at 8:48
  • I'm not sure to what you are referring :-| Could you elaborate more about how Ctrl+t should be mentioned in the answer? Did the suggestions proposed in the answer helping you? What are your remaining problems :-) Commented Jun 12 at 9:10
  • 1
    @user17227456 Ctrl-T was just a typo. "R" and "T" are next to one another on the keyboard. I edited and fixed it.
    – Friedrich
    Commented Jun 12 at 11:23
  • Thanks @Friedrich you are my guardian angel :-) Commented Jun 12 at 11:30
  • 2
    Related: vi.stackexchange.com/a/27814/10604
    – D. Ben Knoble
    Commented Jun 12 at 14:50
0

A simplistic way to achieve the same result—with a little bit more of manual work—is to use :substitute's g and c flags. Using g will replace every occurrence on the line, not just the first. The c flag prompts the user for confirmation for each substitution. See :help :s_flags.

On the following line

To be or not to be

with the cursor on the first "be", run the command

:s/<C-R><C-W>/& a bee/cg

When asked for confirmation, reply n to keep the first "be" and y to replace the second one.

While this lacks the precision of Vivian's answer, I'd argue that the gc flags are more valuable in everyday "replace all (except this)" editing tasks.


Totally unrelated non-disclaimer: originally I wanted ChatGPT to come up with a line with a repeated word but I had trouble signing in and my patience wore out after 30 seconds. No AI tools were used in writing this post. And sorry for using the lamest of Hamlet puns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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