【问题标题】:Replacing placeholders with SED用 SED 替换占位符
【发布时间】:2017-09-11 08:52:23
【问题描述】:

我正在尝试用属性文件中的值替换 html 文件中的 [[****]] 占位符。

输入文件中的示例内容:

<html>
<host>[[my_host]]</host>
<port>[[my_port]]</port>
</html>

属性文件中的示例内容:

my_host=linkcmb.com
my_port=8080

我当前的脚本:

#/bin/sh

property_file=$1
input_html=$2
output_html=$3

IFS="="
while read k v || [[ -n "$k" ]]; do
  test -z "$k" && continue 
  declare $k=$v
done <"$property_file"

eval "$(sed 's/\[\[\([^]]\+\)\]\]/${\1}/g' $input_html) >$output_html";

错误:Html 标签也被评估导致错误。

./some.sh: line 32: html: No such file or directory
./some.sh: line 33: host: No such file or directory
./some.sh: line 35: /host: No such file or directory   
....
....

任何建议将不胜感激。谢谢。

【问题讨论】:

  • 为清晰起见添加示例输入行和预期输出...并且 sed 不是用于 html 文件的合适工具...
  • @Sundeep 更新问题,请检查
  • imo,这不适合 bash 脚本和 sed...我没有使用适当的 html 解析器的经验...对于给定的示例,sed -f &lt;(sed 's/^\([^=]*\)=\(.*\)/s|\\[\\[\1\\]\\]|\2|/' property.txt) ip.html 可能有效,但它很容易打破实际用例
  • sh 不是bash

标签: linux bash shell sed scripting


【解决方案1】:

你可以用

替换你的while循环
. "$property_file"

不过,我不喜欢eval,而且你不需要声明这些设置。
你想要sed 之类的命令

sed '/=/ s/\([^=]*\)=\(.*\)/s#\\\[\\\[\1\\\]\\\]#\2#g/' "$property_file"

很多反斜杠,[[]] 是一个艰难的选择。
您可以使用进程替换来使用这些命令:

sed -f <(
   sed '/=/ s/\([^=]*\)=\(.*\)/s#\\\[\\\[\1\\\]\\\]#\2#g/' "$property_file"
        ) "${input_html}"

【讨论】:

  • 完美!!谢谢你的建议。 :)
【解决方案2】:

sed 中缺少一个正则表达式选项,但它存在于 perl 中。如果您可以使用 perl,则 \Q 和 \E 之间的任何内容都会被转义并按字面​​意思理解。

脚本需要更改以创建一个包含所有替换命令的临时 perl 文件。应该是这样的:

#/bin/sh

property_file=$1
input_html=$2
output_html=$3

perlfile="$$.perl"

IFS="="
while read k v || [[ -n "$k" ]]; do
  test -z "$k" && continue
  echo "s/\Q[[${k}]]\E/${v}/g;" >> $perlfile
done <"$property_file"

perl -p  $perlfile $input_html  >$output_html

rm $perlfile

编辑: 如果您的某个属性包含斜杠(例如,路径名),您可以直接在属性文件中对其进行转义:

# input
<path>[[my_path]]</path>

# properties
mypath=dir\\/filename

# output
<path>dir/filename</path>

反斜杠也一样:

# input
<path>[[my_path]]</path>

# properties
mypath=dir\\\\filename

# output
<path>dir\filename</path>

否则,您可能需要在脚本中添加逻辑才能执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-07
    • 2013-01-24
    • 2018-12-16
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    相关资源
    最近更新 更多