regex – Perl / Sed命令多次替换相同的模式

前端之家收集整理的这篇文章主要介绍了regex – Perl / Sed命令多次替换相同的模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要使用perl或sed等命令在/etc/xinetd.d/chargen中设置disable = no.

/etc/xinetd.d/chargen内容是:

# description: An xinetd internal service which generate characters.  The
# xinetd internal service which continuously generates characters until the
# connection is dropped.  The characters look something like this:
# !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg
# This is the tcp version. 
service chargen
{
        disable         = yes
        type            = INTERNAL
        id              = chargen-stream
        socket_type     = stream
        protocol        = tcp
        user            = root
        wait            = no 
}

# This is the udp version. 
service chargen
{
        disable         = yes
        type            = INTERNAL
        id              = chargen-dgram
        socket_type     = dgram
        protocol        = udp
        user            = root
        wait            = yes 
}

我用过perl命令

 perl -0777 -pe 's|(service chargen[^\^]+)disable\s+=\syes|\1disable=no|' /etc/xinetd.d/chargen

但它只在一个地方取代.

# description: An xinetd internal service which generate characters.  The
# xinetd internal service which continuously generates characters until the
# connection is dropped.  The characters look something like this:
# !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg
# This is the tcp version.
service chargen
{
        disable         = yes
        type            = INTERNAL
        id              = chargen-stream
        socket_type     = stream
        protocol        = tcp
        user            = root
        wait            = no
}

# This is the udp version.
service chargen
{
        disable=no
        type            = INTERNAL
        id              = chargen-dgram
        socket_type     = dgram
        protocol        = udp
        user            = root
        wait            = yes
}

什么是让它在两个地方都有效的正确命令?

注意:我可以用disable = no替换disable = yes而不匹配服务chargen但是我需要在/etc/xinetd.conf中使用相同的sed / perl命令来替换其他服务.

更新正如Jonathan在评论中强调的那样,禁用可以位于花括号内的任何位置.

解决方法

使用sed,您可以使用:

sed -e '/^service chargen/,/^}/ { /disable *= yes/ s/yes/no/; }'

第一部分搜索从一个起始服务chargen到第一行的行的范围,然后以}开头;在该范围内,它查找包含disable = yes的行,其中disable和= yes之间有任意数量的空格,并将yes更改为no.如果有必要,你可以使正则表达式更繁琐(没有尾随空格;不编辑服务chargen2018块,要求}没有尾随空白等)但它可能没有必要.

您通常可以进行就地编辑,但要注意系统之间在如何执行此操作的语义上的差异. (BSD和macOS需要-i”; GNU只需要-i;两者都接受-i.bak,两者意味着相同 – 但你有一个备份文件要清理.)

猜你在找的Perl相关文章