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

Jakub Narębski picture Jakub Narębski · Oct 29, 2009 · Viewed 7.7k times · Source

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.

Answer

Dennis Williamson picture Dennis Williamson · Oct 29, 2009

You can use csplit:

echo "a
b
c

d
e
f" | csplit -s - '/^$/'

Or

csplit -s filename '/^$/'

(assuming the contents of "filename" are the same as the output of the echo) would create, in this case, two files named "xx00" and "xx01". The prefix can be changed from "xx" to "outfile", for example, with -f outfile and the number of digits in the filename could be changed to 3 with -n 3. You can use a more complex regex if you need to deal with Macintosh line endings.

To split a file at each empty line, you can use:

csplit -s filename '/^$/' '{*}'

The pattern '{*}' causes the preceding pattern to be repeated as many times as possible.