5

I've got a list like below:

words
more words
here's more

skip space
words here
bananza!


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)

3 Answers 3

11

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

8
  • 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, 2011 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, 2011 at 19:18
  • s// is line-based; couldn't you just do s/^\(.\+\)$/* \1/? Oct 12, 2011 at 19:24
  • 4
    That's too complicated, this works: :%s/^./* &/
    – Heptite
    Oct 12, 2011 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, 2011 at 16:08
5

Try

: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/$/ */
1
  • Thanks! These are great and I've figured out a few things just playing around with them!
    – Rob
    Oct 15, 2011 at 16:08
2

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

:g/./s/^/*

Explanation

:g/ Global Substitute begin search for pattern

. Match any character except new line :help /.

/^ Match start of line

/* Insert the *

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .