Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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)

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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

share|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
show 3 more comments

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/$/ */
share|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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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