【问题标题】:Is there a way within bash to replace placeholders in a text file with the contents of variables?bash 中有没有办法用变量的内容替换文本文件中的占位符?
【发布时间】:2013-04-20 05:44:28
【问题描述】:

在 bash 中有没有办法用变量的内容替换文本文件中的占位符?

例如,我想发送一封电子邮件通知,如下所示:

Dear Foo, 

Alert: <Alert error text 1> 

<Alert error text 2>

blah blah blah blah blah blah

我看到了一篇相关文章 (How to replace ${} placeholders in a text file?),但在示例中,它添加了静态内容。问题是“alert error text 1”和“alert error text 2”总是在变化。我不知道使用 SED/AWK 将标记替换为动态内容的方法。

这可能吗?

【问题讨论】:

    标签: bash sed awk centos


    【解决方案1】:

    您是否看到此处发布的旧解决方案可以处理命令替换?

    https://stackoverflow.com/a/17030953/1322463

    eval "cat <<EOF $(<template.txt) EOF " 2> /dev/null

    所以模板可以包含以下内容: Hello $USER, Today is $(date)

    输出: Hello plockc, Today is Sun Jun 26 13:16:28 PDT 2016

    只要确保您控制模板,否则任何运行的东西都会以您的用户身份运行。

    【讨论】:

      【解决方案2】:

      这可能对你有用:

      template () {
      cat <<!
      Dear $1,
      
      I'm fine, hope you are too.
      
      Love $2
      !
      }
      
      template foo bar
      

      【讨论】:

        【解决方案3】:

        这似乎是printf 的工作:

        template="Dear Foo, 
        
        Alert: %s 
        
        %s
        
        %s"
        
        # Prior to bash 4
        instance=$(printf "$template" "$AlertText1" "$AlertText2" "$Body")
        
        # Bash 4+
        printf -v instance "$template" "$AlertText1" "$AlertText2" "$Body"
        

        【讨论】:

        • printf-v 选项出现在 Bash 3.1 中。
        【解决方案4】:
         sed -e 's/<Alert error text 1>/'$e1'/' -e 's/<Alert error text 2>/'$e2'/' file.txt
        

        其中 $e1 和 $e2 是变量。

        【讨论】:

        • 我试过了,但它似乎不起作用 - 如果警报错误文本有简单的字母数字输出,它工作正常。但在某些情况下,它有额外的特殊字符,当它出现时,它在最终输出中似乎是空白的。有没有办法帮助 sed 处理具有特殊字符的可变内容?
        【解决方案5】:
        e1=dog
        e2=bird
        sed "
        s/<Alert error text 1>/$e1/
        s/<Alert error text 2>/$e2/
        "
        

        【讨论】:

        • 我试过了,但它似乎不起作用 - 如果警报错误文本有简单的字母数字输出,它工作正常。但在某些情况下,它有额外的特殊字符,当它出现时,它在最终输出中似乎是空白的。有没有办法帮助 sed 处理具有特殊字符的可变内容?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-29
        • 1970-01-01
        • 1970-01-01
        • 2020-11-16
        相关资源
        最近更新 更多