Search code examples
linuxunixawkscriptinggnu

Export every line (excpet last line ) of a file to create a new file for each line using AWK


For example if there are n no of lines, then n-1 no of files should be created. Here is what i have achieved so far. I am manually inserting 8 (i.e. total no of lines). I dont know how to get total no of lines in a variable and then use it.

awk '{if (NR<8) F=NR".ndjson"; print >> F; close (F)}' export.ndjson

Solution

  • to print every line to its own file, except the last line.

    $ awk 'p{close(f); f="object"(NR-1)".ndjson"; print p > f} {p=$0}' file
    

    note also that empty lines won't create empty files.

    The logic is simply to delay printing by one record.