Search code examples
shellunixawksplitaix

Split a large file into smaller files using awk with numeric suffix


I am using AIX where split does not has "-d" flag, which will add numbering suffix to the smaller files after splitting.

My only option to do this in one-liner would be using AWK.

I have a large file "main.txt", i want them split and have 2-digit numeric suffix:

What I am able to do :

$ split -l 10 main.txt main_
main_a
main_b
main_c

What i want is :

main_01
main_02
main_03

Solution

  • awk '(NR%10) == 1{close(out); out=sprintf("main_%02d",++c)} {print > out}' file
    

    or to use your input file name as the base for the output files:

    awk '
        NR==1 { base=FILENAME; sub(/\.[^.]*$/,"",base) }
        (NR%10) == 1 { close(out); out=sprintf("%s_%02d",base,++c) }
        { print > out }
    ' file