Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The sed FAQ
Prev Home Next

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.

The sed FAQ
Prev Home Next

 
 
   Reprinted courtesy of Eric Pement. Also available at https://sed.sourceforge.net/sedfaq.html Design by Interspire