【问题标题】:How to use variable in sed command to replace a property value in a property file如何在 sed 命令中使用变量来替换属性文件中的属性值
【发布时间】:2014-06-03 20:26:35
【问题描述】:

我可以使用下面的命令通过硬编码来改变目标的值。

sed -ie s/^target=.*/target=google.com/ url.properties

但如果我使用变量,我就会出错。我不知道 sed 命令是如何工作的。我只需要设置构建系统就可以了。

url = google.com
sed -ie s/^target=.*/target=$url/ url.properties

错误是 sed: -e expression #1, char 25: unterminated `s' command

【问题讨论】:

    标签: linux shell unix centos6


    【解决方案1】:

    问题可能会发生,因为您的 URL 可能包含 / bash 将其解释为 sed 语法,所以像 https/www.google.com 这样的东西最终会变成这样:

    sed -ie 's/^target=.*/target=https/www.google.com/' url.properties
    

    我建议对任何特殊字符进行分隔以避免 sed 被混淆:

    url=google.com
    url=`echo $url | sed -e "s/\//\\\\\\\\\//g"` # delimits backslash in URL's
    sed -ie "s/^target=.*/target=$url/" url.properties
    

    【讨论】:

    • 或者为s///命令使用不同的分隔符:sed -i "s#target=.*#target=$url#" file
    • 是的,这也是一种方式,但 URL 也可以包含 # 符号。
    • url=echo $url | sed -e "s/\//\\\\\//g" sed 出现错误:-e 表达式 #1,字符 9:`s' 的未知选项
    • @user3551469 你能给我url的值吗
    • @snyder 非常感谢。它现在工作了。
    【解决方案2】:

    两个问题:

    • 在 bash 的变量赋值中不能有空格
    • 您必须引用 sed 命令(最好是 url)

    工作示例:

    url="google.com"
    sed -ie "s/^target=.*/target=$url/" url.properties
    

    【讨论】:

      猜你喜欢
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 2016-12-17
      • 2015-06-01
      • 1970-01-01
      • 2011-07-13
      相关资源
      最近更新 更多