Linux Split File (eg CSV) and Keep Header Row

This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

Linux has a great little utility called split, which can take a file and split it into chunks of whatever size you want, eg 100 line chunks.

However, for CSV files etc, each chunk generally needs to have the header row in there. Unfortunately the split command doesn’t have an option for that. However with a little bit more code you can achieve it.


tail -n +2 file.txt | split -l 4 - split_
for file in split_*
do
    head -n 1 file.txt > tmp_file
    cat $file >> tmp_file
    mv -f tmp_file $file
done