shellsedportabilitytext-manipulationfilesplitting

How to split file on first empty line in a portable way in shell (e.g. using sed)?


I want to split a file containg HTTP response into two files: one containing only HTTP headers, and one containg the body of a message. For this I need to split a file into two on first empty line (or for UNIX tools on first line containing only CR = '\r' character) using a shell script.

How to do this in a portable way (for example using sed, but without GNU extensions)? One can assume that empty line would not be first line in a file. Empty line can got to either, none or both of files; it doesn't matter to me.


Solution

  • $ cat test.txt
    a
    b
    c
    
    d
    e
    f
    $ sed '/^$/q' test.txt 
    a
    b
    c
    
    $ sed '1,/^$/d' test.txt 
    d
    e
    f
    

    Change the /^$/ to /^\s*$/ if you expect there may be whitespace on the blank line.