Search code examples
vimconditional-statementsmovelines

How to conditionally move lines up?


I have a text file with many lines.

test = 
more text more text more text more text
more text more text more text more text
... etc....
more text more text more text more text
more text more text more text more text
1 text
test2 =
more text more text more text more text
more text more text more text more text
3 more text

etc

What I want to do is to move lines up starting with a number and attach them after the first line found (going backwards) ending with '=\s'

expected output:

test = 1 text
more text more text more text more text
more text more text more text more text
... etc....
more text more text more text more text
more text more text more text more text
test2 = 3 more text
more text more text more text more text
more text more text more text more text

I have no idea how to do this.
Can someone help me?


Solution

  • Using :global, :norm, :move and the possibility to use a search as target for Ex commands:

    :g/^\d/m?.*=$|norm kJ
    

    Breakdown:

    :g/pattern/command " executes command for every line matching pattern
    ^\d                " pattern for "lines that start with a number"
    m?.*=$             " move matched line to right below the first
                       " line ending with = upward
    |                  " separator between Ex commands
    norm               " execute normal mode command
    kJ                 " go to line above and join