【问题标题】:Replace all occurrences with only one pattern using sed使用 sed 将所有匹配项替换为仅一种模式
【发布时间】:2016-07-24 04:11:33
【问题描述】:

我编写了一个 shell 脚本以在 /etc/ssh/sshd_config 中将 GSSAPIAuthentication 设置为 no。

在我的脚本中,我有这个部分:

if [ $( grep "^GSSAPIAuthentication no$" /etc/ssh/sshd_config >/dev/null; echo $? ) -ne 0 ]; then
    sed -i 's/^[#]*GSSAPIAuthentication.*$/GSSAPIAuthentication no/g' /etc/ssh/sshd_config
fi

这很好用,但它会将所有出现的情况替换为:

#GSSAPIAuthentication no --> GSSAPIAuthentication no

#GSSAPIAuthentication 是 --> GSSAPIAuthentication 否

GSSAPIAuthentication 是 --> GSSAPIAuthentication 否

所以我有多行 GSSAPIAuthentication 没有。如何将其更改为只有一行 GSSAPIAuthentication no?

谢谢。

【问题讨论】:

    标签: shell replace sed


    【解决方案1】:

    我建议使用 awk 来执行此操作:

    awk '/GSSAPIAuthentication/ { if (!seen++) print "GSSAPIAuthentication no"; next } 1' file
    

    这会将包含“GSSAPIAuthentication”的行的第一个实例替换为所需的替换。对于匹配模式的后续行,!seen++ 将为真,因此它们不会被打印,next 会跳到下一条记录。末尾的 1 始终为 true,因此会打印其他行。

    要覆盖现有文件,请使用标准模式 awk '...' /etc/ssh/sshd_config > tmp && mv tmp /etc/ssh/sshd_config(但在您确定您对结果满意之前,我会保留这样做)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 2012-09-19
      • 2011-06-17
      • 2012-05-18
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      相关资源
      最近更新 更多