How to split a file and keep the first line in each of the pieces?

前端 未结 12 800
-上瘾入骨i
-上瘾入骨i 2020-12-07 18:28

Given: One big text-data file (e.g. CSV format) with a \'special\' first line (e.g., field names).

Wanted: An equivalent of the cor

12条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 19:09

    Inspired by @Arkady's comment on a one-liner.

    • MYFILE variable simply to reduce boilerplate
    • split doesn't show file name, but the --additional-suffix option allows us to easily control what to expect
    • removal of intermediate files via rm $part (assumes no files with same suffix)

    MYFILE=mycsv.csv && for part in $(split -n4 --additional-suffix=foo $MYFILE; ls *foo); do cat <(head -n1 $MYFILE) $part > $MYFILE.$part; rm $part; done

    Evidence:

    -rw-rw-r--  1 ec2-user ec2-user  32040108 Jun  1 23:18 mycsv.csv.xaafoo
    -rw-rw-r--  1 ec2-user ec2-user  32040108 Jun  1 23:18 mycsv.csv.xabfoo
    -rw-rw-r--  1 ec2-user ec2-user  32040108 Jun  1 23:18 mycsv.csv.xacfoo
    -rw-rw-r--  1 ec2-user ec2-user  32040110 Jun  1 23:18 mycsv.csv.xadfoo
    

    and of course head -2 *foo to see the header is added.

提交回复
热议问题