【问题标题】:Replace a string with single quotes using sed使用 sed 将字符串替换为单引号
【发布时间】:2020-03-27 09:20:43
【问题描述】:

我正在尝试使用sed 替换大型配置文件中的字符串,但由于自动化要求,需要通过脚本完成。

目前这是我的测试文件 -

# The below line should get modified.
var HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io'];

这是我当前的脚本摘录 -

#/bin/bash
ORIGINSORIGINAL="var HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io'];"

ORIGINS="var HOSTED_VIEWER_ORIGINS = ['https://s3-host1.lab.example.com', 'https://s3-host1.prod.example.com', 'null', 'http://mozilla.github.io', 'https://mozilla.github.io'];"

sed -i "s@${ORIGINSORIGINAL}@${ORIGINS}@g" /tmp/sedtest.txt

由于某种原因,sed 没有匹配到字符串,并且没有发生替换。鉴于原始字符串中包含单引号,我是否有明显遗漏的内容或是否需要转义 sed 命令的一部分。

谢谢!

【问题讨论】:

  • 搜索字符串中的方括号是元字符,必须小心引用。由于您在双引号中使用变量,因此您必须特别小心,并且可能会反引号...
  • @PaulHodges 就是这样 - 转义时的方括号(使用更一般的搜索)使这变得如此简单。谢谢!
  • 大声笑——发布了一个例子,你打败了我。 ;)
  • @PaulHodges 将您的标记标记为正确,因为您已经确定了它 - 再次非常感谢!

标签: bash sed replace


【解决方案1】:

一个简单的解决方案:

$: ORIGINSORIGINAL="var HOSTED_VIEWER_ORIGINS = .*" # no metas
$: ORIGINS="var HOSTED_VIEWER_ORIGINS = ['https://s3-host1.lab.example.com', 'https://s3-host1.prod.example.com', 'null', 'http://mozilla.github.io', 'https://mozilla.github.io'];"
$: sed "s@${ORIGINSORIGINAL}@${ORIGINS}@g" /tmp/sedtest.txt
var HOSTED_VIEWER_ORIGINS = ['https://s3-host1.lab.example.com', 'https://s3-host1.prod.example.com', 'null', 'http://mozilla.github.io', 'https://mozilla.github.io'];

【讨论】:

    【解决方案2】:

    事实证明单引号字符串不是问题,但实际上是方括号没有被正确转义。

    将我的脚本更改为此(转义括号并进行更一般的搜索)就像一个魅力。

    #/bin/bash
    ORIGINSORIGINAL="var HOSTED_VIEWER_ORIGINS = \[.*\];"
    
    ORIGINS="var HOSTED_VIEWER_ORIGINS = ['https://s3-host1.lab.example.com', 'https://s3-host1.prod.example.com', 'null', 'http://mozilla.github.io', 'https://mozilla.github.io'];"
    
    sed -i "s@${ORIGINSORIGINAL}@${ORIGINS}@g" /tmp/sedtest.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 2020-12-23
      • 2011-07-08
      • 1970-01-01
      • 2021-10-04
      • 2019-11-11
      相关资源
      最近更新 更多