Suppose I have the next line


I want to split it into several lines, each containing n commands for example, for n = 4


1 Answer 1


Using :normal

Here’s one way:


:.,+2             # on this line and the two below it,
     norm!        # run the normal mode commands:
          4f,     # move to the fourth comma on the line, and
             a    # append...
              ^M  # a carriage return

Note that the ^M is a literal carriage return, and you enter it into the command line by typing: Ctrl-VEnter

The downside to this approach is you need to know in advance how many lines you’re going to end up with, in order to specify the range of lines on which to run the normal mode commands.

Using :substitute

An alternative, therefore, is to use a :substitute command:


   \v                    # Using ‘very magic’
:s/                      # substitute
                \zs/     # nothing, (i.e. insert, rather than
                         # substituting), that follows:
     (      ){4}         # 4 instances of
      [^,]*              # any amount of characters that aren’t a
                         # comma
           ,             # followed by a comma
                    \r   # with a newline
                      /g # everywhere on the current line

The downside of this approach, is that it uses regular expressions. Now you have two problems.

Using a recursive macro

Don’t like either of the above? Here’s a macro solution:


qqq                     # Clear out register q
   qq                   # Start recording a macro into register q
     4f,                # move to the fourth comma on the line
        a               # append
         <CR><Esc>      # a newline (press Return and Escape here)
                  @q    # play back the macro in register q.
                        # Currently, this is empty, so it does
                        # nothing, but when we’ve finished recording,
                        # this will jump back to the start of the
                        # macro
                    q   # end the recording
                     @q # play back the macro

This approach has no downsides. I love macros!

  • could you please bring me an example
    – juaninf
    Commented Sep 3, 2022 at 19:23
  • @juaninf Sorry, I’m not sure what you mean: an example of what?
    – Rich
    Commented Sep 3, 2022 at 19:30
  • 1
    A more "standard" substitution expression would use &, i.e. s/\v([^,]*,){4}/&\r/g.
    – Quasímodo
    Commented Sep 4, 2022 at 13:21
  • @Quasímodo That’s true! Not sure why I didn’t do that!
    – Rich
    Commented Sep 4, 2022 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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