Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: Split one file into multiple files based on row count

Tags:

vim

windows

I have a text file with 5,000 rows. I need to split it into files with no more than 99 rows each. Can I do this with vim? If not, what are my other options?

like image 437
divided Avatar asked Nov 09 '16 14:11

divided


People also ask

How do you divide a file into multiple based on size and number of lines?

If you want your file to be split based on the number of lines in each chunk rather than the number of bytes, you can use the -l (lines) option. In this example, each file will have 1,000 lines except, of course, for the last one which may have fewer lines.

How do I split a single file into multiple files in Unix?

If you use the -l (a lowercase L) option, replace linenumber with the number of lines you'd like in each of the smaller files (the default is 1,000). If you use the -b option, replace bytes with the number of bytes you'd like in each of the smaller files.

How do I split a file into multiple files?

Open the Zip file. Open the Tools tab. Click the Split Size dropdown button and select the appropriate size for each of the parts of the split Zip file. If you choose Custom Size in the Split Size dropdown list, another small window will open and allow you to enter in a custom size specified in megabytes.

How do I split a large text file into multiple files in Linux?

To split large files into small pieces, we use the split command in the Linux operating system. The split command is used to split or break large files into small pieces in the Linux system. By default, it generates output files of a fixed size, the default lines are 1000 and the default prefix would be 'x'.


1 Answers

First, you define a control variable:

:let i = 1

Then, you write lines 1 to 99 (inclusive) to a file named after the current value of the control variable, cut those line, and increment the control variable;

:exec "1,99w! chunk-" . i|1,99d|let i = i + 1

Repeat as many times as needed:

49@:

This should give you 50 files named chunk-1 to chunk-50.

Since 5000 is not divisible by 99 you will be left with 50 lines. Write them to chunk-51:

:w chunk-51
like image 116
romainl Avatar answered Nov 15 '22 06:11

romainl