Home > front end >  Parse file and replace tags with another file content
Parse file and replace tags with another file content

Time:12-22

Given files:

index.html
incl/body.html (which contains text "<h1>Title</h1>")

I want a script that "compiles" html files (eg index.html) from:

<html>
<body>
<custom:include "incl/body.html" />
</body>
</html>

to

<html>
<body>
<h1>Title</h1>
</body>
</html>

by copying the content of incl/body.html and overwriting the include tag.

I've made this script so far:

for f in build/*.html;
do
    echo Compiling file $f;
    <what to write here>
done
rm -r incl <as this folder is not needed after compilation)

how do I implement this logic?

Edit: The question is a simplified extract from a build and deploy process where static html files are generated. I am aware of Server side includes in various languages, but I need this implemented in bash.

CodePudding user response:

There's quite a few templating languages, for example php:

You write your index.html like this:

<html>
<body>
<?php require "incl/body.html"; ?>
</body>
</html>

Then you run:

php index.html

That'll output:

<html>
<body>
<h1>Title</h1>
</body>
</html>

CodePudding user response:

Please note that this does not parse HTML and relies on the include command to look exactly like in your example (i.e. everything in one line, no extra spaces etc.)

while read l; do 
    if grep -qE '<custom:include "[^"] " />' <<< "$l" ; then
        cat "$(sed -r 's#<custom:include "([^"] )" />#\1#'  <<< "$l")"
    else
        echo "$l"
    fi
done  < input_file

I would usually recommend using a real template engine for this.

  •  Tags:  
  • bash
  • Related