Suppose I have the next line
1,0,10,10,9,7,7,5,41,3,57,7,1,9
I want to split it into several lines, each containing n commands for example, for n = 4
1,0,10,10,
9,7,7,5,
41,3,57,7,
1,9
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityHere’s one way:
:.,+2norm!4f,a^M
:.,+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.
An alternative, therefore, is to use a :substitute command:
:s/\v([^,]*,){4}\zs/\r/g
\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.
Don’t like either of the above? Here’s a macro solution:
qqqqq4f,a<CR><Esc>@qq@q
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!
&
, i.e. s/\v([^,]*,){4}/&\r/g
.
Sep 4, 2022 at 13:21