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 have a text file which looks like this:

A.
text
text
text


A.
more text

more text

A.
more text

I want to join all lines between the "markers" A. so that it looks like:

A.texttexttext
A.more textmore text
A.more text

How can I do this in Vim?

share|improve this question

2 Answers 2

up vote 3 down vote accepted
:%s/\n\(\(A\.$\)\@!.*\)/\1/

Substitute a pattern matching:

  1. newline,
  2. a group containing of

    1. not the string A. directly followed by end-of-line, then
    2. any character until end of line

with:

  • everything matched except the starting newline (i.e. the group above),

and do this globally.

share|improve this answer
1  
Thanks. I have no idea how that thing works, but it seems to! I will have to dissect it carefully. I also found a work around by joining all the lines and then inserting a new line on "A." –  vim noob May 4 '12 at 13:40
    
@vimnoob: See :help \@! in Vim for more info on that part. Otherwise it's straight forward, hopefully, with my explanation. A problem with your approach is that if "A." occurs in the text, though not as an isolated marker line, it will be split upon as if it were originally a marker. In practice it might not be a problem (I don't know what your "real" file looks like), but generically it can cause unwanted behavior if one is not aware of this. –  Daniel Andersson May 4 '12 at 13:45
    
@vimnoob: I read my answer again, and in case you're not familiar with the :%s/// syntax: it's a "search and replace" syntax in Vim. : starts the command, % specifies the whole buffer as the range, s starts a substitution. / is the pattern delimiter (any other character can be used, but / is "standard"). The first / starts the search pattern, the second the replace pattern, and the third ends it. Trailing modifiers are available to specify case insensitivity, etc. \1 represents the grabbed group in the search pattern. :%s/foo/bar/ replaces foo with bar in the file. –  Daniel Andersson May 4 '12 at 16:02
    
Thanks a lot for your help. I just need to research this \@! part as I am familiar with the basic search replace and basic regexp. –  vim noob May 7 '12 at 11:08
    
This is a great answer that I keep coming back to, but I have to confess that most of the time I just end up joining all of the lines and then splitting them. I just don't use \@! quite often enough to get proficient in its use. –  Matt Parker Feb 28 '13 at 16:46

This also works (when the first line starts with A.)

:v/^A/-1j!
share|improve this answer
    
That does work! Nice. +1 –  ZaSter Mar 13 '13 at 23:55

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.