I've got a list like below:

more words
here's more

skip space
words here

D: look
more spaces
and words!

How can I insert things at the beginning of only those lines with text? :%norm 0i* will put * just fine, but since it does all lines, it gets the empty lines, too. Is there any way to do this without having to go back and clear out those blank spaces (I know they'd be just *, so it shouldn't be hard to do, but it is extra work)


Something like this should work:

:%s/^\(.*[^\n]\)$/* \1/

EDIT Since you asked for a breakdown of the regular expression:

:% All lines

s/ Beginning of substitute command; begin pattern

^ Beginning of line

\( Beginning of group we want to preserve. This will be important later.

.* Any number of characters

[^\n] Some character besides newline

\) End of group

$ End of line

/ End of pattern, beginning of substitution

* \1 Insert *, then the first group that we selected on the left.

/ End of substitution and command

| improve this answer | |
  • This worked! :D Can you explain how it works, though? I'm not great at regex (read I don't know any) but would like to be able to 'get' this. Thanks! – Rob Oct 12 '11 at 19:13
  • Actually, it grabs the first of the double blank lines. D: I'll see if that's just my fault though. EDIT: nope, apparently a blank line that has a blank line under it isn't blank. D: – Rob Oct 12 '11 at 19:18
  • s// is line-based; couldn't you just do s/^\(.\+\)$/* \1/? – Christian Mann Oct 12 '11 at 19:24
  • 4
    That's too complicated, this works: :%s/^./* &/ – Heptite Oct 12 '11 at 19:52
  • 1
    @Heptite, blank lines consisting of a space character would also match. Probably best to specify only lines that contain a non-blank character by using /.*\S.*/ – Firstrock Oct 14 '11 at 16:08


:g/\S/s/^/* /

g/\S/ is a range operator (analogous to % except it selects all lines with a non-blank character).

s/^/* / inserts "* " at the beginning of each selected line.

This avoids the issue with @objectified's answer of putting the prefix on the 1st line of a double blank line sequence.

The following appends " *" at the end of each selected line.

:g/\S/s/$/ */
| improve this answer | |
  • Thanks! These are great and I've figured out a few things just playing around with them! – Rob Oct 15 '11 at 16:08

If the blank line are truly empty, containing only NewLine then this works.



:g/ Global Substitute begin search for pattern

. Match any character except new line :help /.

/^ Match start of line

/* Insert the *

| improve this answer | |

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.