Split CSV file & keep header line using Terminal on Mac

Looking to split a CSV file but keep the header line using Terminal on Mac? All you need is to run this shell script accordingly.

Splitting a CSV file but keeping the first line


In order to split your CSV file but keep the first header line, you need to create a Shell script first.

  1. Open your code editor.
  2. Type in the below script and change the number of lines (currently set to 7500) and file name (currently set to mycsvfile.csv) accordingly.
  3. Save the file in the same directory as your CSV file as split.sh.
HDR=$(head -1 $FILENAME)
split -l 7500 $FILENAME xyz
for f in xyz*
     if [ $n -gt 1 ]; then 
          echo $HDR > Part${n}.csv
     cat $f >> Part${n}.csv
     rm $f


Once you’ve done this, open up Terminal on your Mac and navigate to your split.sh script accordingly and run the sh command (see below).

Note, it’s important to have a backup of your CSV file before running the below command:

sh split.sh