pcoughlin
12/6/2016 - 12:55 AM

Split CSV/Text type file with header line into multiple files with header Line copied to each.

Split CSV/Text type file with header line into multiple files with header Line copied to each.

#!/bin/bash
# Split files with Header intact
#
# $1 is File to Split
# $2 is Number of lines in each split.
# $3 (optional) is split File Prefix
#
if [ "$1" == "" ]; then
  echo $'\n'
  echo 'ERROR: Param 1 is FileName to split' $'\n'
  echo '       Param 2 is number of lines for each split file.' $'\n\n'
  echo '       Param 3 is Split filename prefix.' $'\n\n'
  exit
fi
if [ "$2" == "" ]; then
  echo $'\n'
  echo 'ERROR: Param 1 is FileName to split' $'\n'
  echo '       Param 2 is number of lines for each split file.' $'\n\n'
  echo '       Param 3 is Split filename prefix.' $'\n\n'
  exit
fi
echo Run the script.

tail -n +2 $1 | split -l $2 - _S_
for file in _S_*
do
    head -n 1 $1> _SX_tmp_file
    cat $file>> _SX_tmp_file
    mv -f _SX_tmp_file $1.$file.csv
done

rm _S_*