Renry
Renry

Reputation: 33

Split file into X amount of even sized files?

I have found multiple ways to split files into X amount of lines or X size but I was wondering how do I split a file into 5 evenly sized files for example?

This will be for .csv file if that matters.

Upvotes: 2

Views: 819

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84561

You will want to look at wc -l and split. Putting them together you get:

split -l $(($(wc -l <myfile.txt)/5)) myfile.txt

That will split myfile.txt into 5 even sized files (assuming myfile lines are divisible by 5). default output to xaa, xab .... You can set the suffixes with the -a, -d and --additional-suffix=suffix options.

Another method of splitting is into chunks which will provide even line number of chunks until the last file and dump any excess (non-divisible by 5) lines there.

split -n 5 myfile.txt

You can use the -b option to split into an even number of bytes, but that doesn't sound good for a .csv file.

Upvotes: 2

Maxime Ch&#233;ramy
Maxime Ch&#233;ramy

Reputation: 18831

You can split a files into files of N lines with:

split -l [number of lines] inputfile

So you just need to compute the numbers of lines to obtain 5 files:

ln=$(wc -l < inputfile)
split -l $((ln / 5 + (ln % 5 > 0))) inputfile

Upvotes: 0

Related Questions