【问题标题】:Unknown option to s when trying to replace line with # [duplicate]尝试用#替换行时s的未知选项[重复]
【发布时间】:2016-03-01 22:11:47
【问题描述】:

在 bash 脚本中,我试图用新文本替换以注释开头的行。 sed 无法告诉我哈希字符是 Unknown option to s

sed -i -e "s/#a line/the new line with some $varname/g" "path/to/filename"

我在 # 上尝试了一个反斜杠,但无济于事。如何在 sed 中使用哈希,是的,我必须使用双引号来管理变量的使用。

【问题讨论】:

    标签: bash shell sed


    【解决方案1】:

    问题与#无关。您收到错误是因为您注入到 sed 脚本中的变量恰好包含 / 字符。如果您知道一个绝对不会出现在模式或替换中的字符,请将其用作s 命令的分隔符。例如。假设| 是安全的:

    sed "s|#a line|the new line with some $varname|" file > file.tmp &&
    mv file.tmp file
    

    或者,c 命令可用于更改整行:

    sed "/#a line/c\\
    the new line with some $varname" file > file.tmp &&
    mv file.tmp file
    

    或者更好的是,找到一种无需将数据注入代码的方法(例如 ed、ex 或 awk)

    【讨论】:

    • 做到了!如果您添加一行显示新分隔符的代码以供将来参考,我会接受!
    猜你喜欢
    • 2013-04-28
    • 2016-03-19
    • 2014-05-31
    • 1970-01-01
    • 2014-09-02
    • 2016-08-16
    • 2013-06-06
    • 2014-04-06
    • 2020-11-25
    相关资源
    最近更新 更多