Shell – Find and replace with contents of a file

filesshell-scripttext processing

I have a file that begins with a few "include" statements, like this:

include foo.xyz
include bar.xyz
do c
do d

Suppose the file foo.xyz contains do a and the file bar.xyz contains do b. How can I write a script that replaces each include file.xyz statement with the contexts of file.xyz? I want to end up with the following output:

do a
do b
do c
do d

I tried the solution in "Replace string with contents of a file using sed" but there the filename is hard-coded. I would like the filename to be dynamically generated, depending on the include argument.

Best Answer

Here's a simple recursive version with awk. You must create a script in your PATH with

#!/bin/bash
awk '
$1=="include" && NF>=2 {
   system("'$0' " $2)
   next
}
{print}' "$@"

It assumes filenames have no special chars (including spaces) in them. The awk checks the first word for include, then calls the script to process the file given as 2nd word. Other lines are printed. Note that the $0 here is outside the single quotes of the awk, so is a shell $0, ie the script name.

Related Question