4.44. How do I emulate file-includes, using sed?
Given an input file with file-include statements, similar to
C-style includes or "server-side includes" (SSI) of this format:
This is the source file. It's short.
Its name is simply 'source'. See the script below.
<!--#include file="ashe.inc"-->
And this is any amount of text between
<!--#include file="jesse.inc"-->
This is the last line of the file.
How do we direct sed to import/insert whichever files are at the
point of the 'file="filename"' token? First, use this file:
#n
# filename: incl.sed
# Comments supported by GNU sed or ssed. Leading '#n' should
# be on line 1, columns 1-2 of the line.
/<!--#include file="/ { # For each "include file" command,
=; # print the line number
s/^[^"]*"/{r /; # change pattern to 'r{ '
s/".*//p; # delete rest to EOL, print
# and a(ppend) a delete command
a\
d;}
}
#---end of sed script---
Second, use the following shell script or DOS batch file (if
running a DOS batch file, use "double quotes" instead of 'single
quotes', and use "del" instead of "rm" to remove the temp file):
sed -nf incl.sed source | sed 'N;N;s/\n//' >temp.sed
sed -f temp.sed source >target
rm temp.sed
If you have GNU sed or ssed, you can reduce the script even further
(thanks to Michael Carmack for the reminder):
sed -nf incl.sed source | sed 'N;N;s/\n//' | sed -f - source >target
In brief, the script replaces each filename with a 'r filename'
command to insert the file at that point, while omitting the
extraneous material. Two important things to note with this script:
(1) There should be only one '#include file' directive per line, and
(2) each '#include file' directive must be the only thing on that
line, because everything else on the line will be deleted.
Though the script uses GNU sed or ssed because of the great support
for embedded script comments, it should run on any version of sed.
If not, write me and let me know.