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

前端 未结 12 794
-上瘾入骨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 18:48

    This is a more robust version of Denis Williamson's script. The script creates a lot of temporary files, and it would be a shame if they were left lying around if the run was incomplete. So, let's add signal trapping (see http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_12_02.html and then http://tldp.org/LDP/abs/html/debugging.html) and remove our temporary files; this is a best practice anyways.

    trap 'rm split_* tmp_file ; exit 13' SIGINT SIGTERM SIGQUIT 
    tail -n +2 file.txt | split -l 4 - split_
    for file in split_*
    do
        head -n 1 file.txt > tmp_file
        cat $file >> tmp_file
        mv -f tmp_file $file
    done
    

    Replace '13' with whatever return code you want. Oh, and you should probably be using mktemp anyways (as some have already suggested), so go ahead and remove 'tmp_file" from the rm in the trap line. See the signal man page for more signals to catch.

提交回复
热议问题