Split file by number of lines including header in each one

With gnu split you could save the header in a variable then split starting from the 2nd line, using the --filter option to write the header first and then the 99 lines for each piece and also specify the output directory (e.g. path to/output dir/):

header=$(head -n 1 infile.txt)
export header
tail -n +2 infile.txt | split -l 99 -d --additional-suffix=.txt \
--filter='{ printf %s\\n "$header"; cat; } >path\ to/output\ dir/$FILE' - file_

this will create 100-lines pieces as

path to/output dir/file_01.txt
path to/output dir/file_02.txt
path to/output dir/file_03.txt
..............................

awk 'NR==1        {a=$0}
    (NR-1)%100==0 {print a > "d/file_" int(1+(NR-1)/100)}
                  {print   > "d/file_" int(1+(NR-1)/100)}' 

Works for me in bash:

lines=100; { read header && sed "1~$((${lines}-1)) s/^/${header}\n/g" | split -l $lines --numeric-suffixes=1 --additional-suffix=.txt - file_ ; } < inputfile.txt

Tags:

Split

Awk

Files