4

Let's say I have these lines:

a
# c
b
## d

and i want to insert # on a line starting with a # so that I get this:

a
## c
b
### d

I was not able to find anything in the vim help, but I was able to get this far: g/^#/ - what should come after the second /?

5
  • 2
    While the question is technically not the same, I suspect your need is identical to one expressed in that Q/A (vi.stackexchange.com/questions/13065/…). Am I right? – Luc Hermitte Aug 17 '17 at 0:31
  • Using substitute Isn't exactly the samebecause if there is a hash in the middle of the line and that would also be changed – Dylanthepiguy Aug 17 '17 at 3:42
  • 2
    No it won't. The pattern to search isn't # but ^#. :substitute really is the way to go. Beside that wasn't my question. My question is: what's your exact need? Is it about refactoring markdown? – Luc Hermitte Aug 17 '17 at 7:15
  • Ah I see, my bad. And yes I am refactoring markdown. I guess it is almost duplicate question then? – Dylanthepiguy Aug 17 '17 at 19:28
  • In spirit yes. Other people may be interested in the technical solution that mixes global + normal, though. What's interesting in the other question, is that the objective is more extensively covered. For instance, I provide a non trivial way to refactor headings while leaving shebangs and # comments intact in code snippets when that matters. – Luc Hermitte Aug 17 '17 at 22:26
11

What comes after the second / is an Ex command. In this case you could use the :normal command, which executes its argument as if you typed it in normal mode (see :help :normal)

:g/^#/normal I#

or the :substitute command (see :help :substitute)

:g/^#/substitute/^/#/
" Or just
:g/^#/s/^/#/

but also you could use the :substitute command without the :g like so:

:%s/^\ze#/#/
" or
:%s/^#/#&/

See :help /\ze and :help s/\& for more information.

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.