【问题标题】:Replace token in a file with any content用任何内容替换文件中的令牌
【发布时间】:2019-12-15 05:46:52
【问题描述】:

作为最终结果,我想将文件input.html 中的几行文本复制到output.html

input.html

 <body>
   <h1>Input File</h1>
   <!-- START:TEMPLATES -->
   <div>
      <p>Lorem Ipsum &amp; Lorem Ipsum</p>
      <span>Path: /home/users/abc.txt</span>
   </div>
   <!-- END:TEMPLATES -->
 <body>

template.html

 <body>
   <h1>Template File</h1>
   <!-- INSERT:TEMPLATES -->
   <p>This is a Text with &nbsp; &amp; /</p>
 <body>

我在PowershellBash 中尝试了不同的方法来完成这项工作。但没有成功。

通过以下方式成功地将输入输入到变量中:

content="$(sed -e '/BEGIN:TEMPLATES/,/END:TEMPLATES/!d' input.html)"`

但是在另一个文件中替换是不可能的。我试过sedawk。如果变量包含任何特殊字符,例如 &amp; /,这两个问题都会有很多问题...

output.html

 <body>
   <h1>Output File</h1>
   <div>
      <p>Lorem Ipsum &amp; Lorem Ipsum</p>
      <span>Path: /home/users/abc.txt</span>
   </div>
   <p>This is a Text with &nbsp; &amp; /</p>
 <body>

感谢您提供任何有助于解决我的问题的意见。

【问题讨论】:

  • Bash 还是 PowerShell?
  • @BenjaminW。 Powershell 中的首选。但是在 Linux 机器上构建很容易,所以如果你有一个 bash 解决方案,那么我会选择那个。
  • Shell 脚本听起来就像是模板标记语言(如 HTML)的错误工具。各种语言都有很多更好的模板引擎,即使是历史悠久的 Apache 的服务器端包含也会做得更好。

标签: bash powershell cmd


【解决方案1】:

如果 START/END cmets 在单独的行上,我会为输入文件构建一个简单的解析器,如下所示:

$inTemplate = $false
$template = switch -Wildcard -File '.\input.html' {
  '*<!-- START:TEMPLATES -->*'{
    $inTemplate = $true
  }
  '*<!-- END:TEMPLATES -->*'{
    $inTemplate = $false
  }
  default{
    if($inTemplate){
      $_
    }
  }
}

现在我们可以对模板文件做同样的事情:

$output = switch -Wildcard -File '.\template.html' {
  '*<!-- INSERT:TEMPLATES -->*'{
    # return our template input
    $template
  }
  default{
    # otherwise return the input string as is
    $_
  }
}

# output to file
$output |Set-Content output.html

【讨论】:

    【解决方案2】:

    用 awk 解决。

    &lt;!-- START:TEMPLATES --&gt;&lt;!-- END:TEMPLATES --&gt; 之间的文件input.html 中获取所有行,并将其存储在数组insert_var 中。

    END 部分,在while 循环中逐行打印template.html。如果行包含&lt;!-- INSERT:TEMPLATES --&gt;,则打印数组insert_var的内容。

    输出被重定向到output.html

    据我所知,awk 不会弄乱那些特殊字符。

    awk -v temp_file="template.html" '
    
    BEGIN{input_line_num=1} 
    
    /<!-- END:TEMPLATES -->/{linestart=0}
    { if(( linestart >= 1)) {insert_var[input_line_num]=$0; input_line_num++}}
    /<!-- START:TEMPLATES -->/{linestart=1} 
    
    END{ while ((getline<temp_file) > 0) 
        {if (( $0 ~ "<!-- INSERT:TEMPLATES -->")) 
            {for ( i = 1;i < input_line_num; i++) {print insert_var[i]}} 
        else { print } }}
    ' input.html > output.html
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 2023-04-11
      • 1970-01-01
      相关资源
      最近更新 更多