Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split text file into smaller multiple text file using command line

I have multiple text file with about 100,000 lines and I want to split them into smaller text files of 5000 lines each.

I used:

split -l 5000 filename.txt 

That creates files:

xaa xab aac xad xbe aaf 

files with no extensions. I just want to call them something like:

file01.txt file02.txt file03.txt file04.txt 

or if that is not possible, i just want them to have the ".txt" extension.

like image 854
ashleybee97 Avatar asked Aug 11 '14 17:08

ashleybee97


People also ask

How do I split multiple files in Linux?

To split a file equally into two files, we use the '-n' option. By specifying '-n 2' the file is split equally into two files.


1 Answers

I know the question has been asked a long time ago, but I am surprised that nobody has given the most straightforward unix answer:

split -l 5000 -d --additional-suffix=.txt $FileName file 
  • -l 5000: split file into files of 5,000 lines each.
  • -d: numerical suffix. This will make the suffix go from 00 to 99 by default instead of aa to zz.
  • --additional-suffix: lets you specify the suffix, here the extension
  • $FileName: name of the file to be split.
  • file: prefix to add to the resulting files.

As always, check out man split for more details.

For Mac, the default version of split is apparently dumbed down. You can install the GNU version using the following command. (see this question for more GNU utils)

brew install coreutils 

and then you can run the above command by replacing split with gsplit. Check out man gsplit for details.

like image 95
ursan Avatar answered Oct 08 '22 13:10

ursan