【问题标题】:Bash sed -i update with trailing backslashBash sed -i 使用尾随反斜杠更新
【发布时间】:2017-10-06 10:23:16
【问题描述】:

我想运行这个:

sed -i -e "s/\($user hard nproc \).*/\1{value here ending with /}/" /etc/something.conf

这里,{value here 以 /} 结尾就像 100/abc/

但是,如果我只是把/喜欢:

sed -i -e "s/\($user hard nproc \).*/\1abc//" /etc/something.conf

我得到这个错误: `s' 的未知选项

我一直在努力解决这个问题,但想不出任何解决方案...

基本上我要做的是更新我的旧值 "用户名 hard nproc 10" 到“用户名 hard nproc 10**” 用“**”。

【问题讨论】:

  • 欢迎来到 Stack Overflow,你的问题不清楚。请在代码标签中发布带有预期输出文件的示例 Input_file,然后让我知道。
  • 相应更新。

标签: bash shell unix sed bin


【解决方案1】:

您需要转义尾部斜杠或为表达式使用不同的字符。即:

sed -i "s/\($user hard nproc \).*/\1abc\//" /etc/cgrules.conf

sed -i "s#\($user hard nproc \).*#\1abc/#" /etc/cgrules.conf

【讨论】:

【解决方案2】:

遵循简单的 sed 对我很有效。

echo "username hard nproc 10" | sed 's/username hard nproc 10/username hard nproc 10**/g'
username hard nproc 10**

假设您希望将这些旧值和新值放入变量中,那么以下可能对您有所帮助。

old_value="username hard nproc 10"
new_value="username hard nproc 10**"
echo "username hard nproc 10" | sed "s/$old_value/$new_value/g"

输出如下。

username hard nproc 10**

同样,您可以在此处提及您的 Input_file,尽管有回声。如果您想保存 Input_file 本身的更改,也可以使用 sed-i 选项(我建议在不更改 Input_file 的情况下运行上面的代码,然后在您对结果满意后使用 -i 选项运行)。

【讨论】:

    【解决方案3】:

    在 sed 中,每当您想使用 / 做某事而妨碍用于命令的 / 时,最简单的做法是为命令使用不同的分隔符。例如:

    sed -e "s@\($user hard nproc \).*@\1{value here ending with /}@"
    

    可以正常工作。 s/pattern/repl/flags 只是一个约定,你也可以使用s@pattern@repl@flags

    【讨论】:

      猜你喜欢
      • 2020-05-20
      • 1970-01-01
      • 2021-05-06
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多