使用bash脚本将sqlite输出渲染到模板文件中

时间:2014-07-21 10:33:21

标签: bash sqlite templates sed

我有template - 就像文件一样,里面有一些简单的HTML。

<html>
    <head>
        <meta charset="utf-8">
        <title>stackoverflow.com</title>
        <link rel="stylesheet" href="/css/master.css" type="text/css" media="screen" title="no title" charset="utf-8">

    </head>
    <body id="container">
    <table border="0" cellspacing="5" cellpadding="5">
        <tr>
            <th>Field 1 Label</th>
            <th>Field 2 Label</th>
            <th>Field 3 Label</th>
        </tr>

        <!-- ...dynamically generated content from other file should go here... -->
        <!-- ...instead of this template tag... -->
        ${sqlite_html_output} <!-- this is a placeholder I want to use -->

    </table>


    </body>
</html>

我要渲染到此模板中的文件将是以下函数中包含的 sqlite 查询的输出:

function generate_report() {

    sqlite3 -batch database.db <<- "end_of_message"
        .mode html
        .output o.html # <-- this is the name of generated output file
        select field1,field2,field3 from tbl;
    end_of_message

    #..here I want to use `sed` to embed content of o.html file, into my template
}

所以在我的generate_report函数中,我想使用sed来渲染o.html 将文件放入我的模板,代替${sqlite_html_output} template-tag占位符。

这可能吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

sed '/\${sqlite_html_output}/{r o.html
    d;}' template_file

它应搜索与${sqlite_html_output}匹配的行,并在匹配时插入从o.html读取的文本,然后删除行的内容(例如,在您的示例中为${sqlite_html_output} <!-- this is a placeholder I want to use -->)。

换行is mandatory