I recently migrated my monolithic zshrc into “part files”. I wanted to do that by delimiting regions and processing those regions into separate files.

I learned about csplit, which can do that given a delimiter. However, csplit has no affordance for setting the filename – every new section is a new file, with an autoincrementing number.

Here’s a way to do it with gawk.

It expects a file delimited with #: filename lines into multiple files, each of which is named by the filename specified in the delimiter. If the same filename is encountered twice, the script will append the new lines to it.

Sources:

Script

#!/bin/sh
true + /; exec gawk -f "$0" -- "$@"; / {}
# awk script starts here
BEGIN {out="_"}
$1 == "#:" {if ($2 ~ /\//) exit(1); out=$2; next}
{print >out}