bowei_99 has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to update a series of ntp.conf files, which have lines like the following, followed by what it should change to (brackets show the strings may or may not be there):

server old-ip-or-hostname-here prefer [burst iburst]
change to:
server new-ip-here prefer burst iburst server another-ip-or-hostname-here [burst iburst]
change to:
nothing (remove the line)
as well as, in some cases,
server 127.127.1.0
occurs, and it should be leave as is, i.e. no change.

So, I try the following for the first:

perl -p -i -e 's/server [\w\.]+ prefer.*/server new-ip-here prefer bur +st iburst/g' ntp.conf
but I'm not sure how to write the regexp for the second without removing lines for 127.127.1.0.

I'm running this from a shell script, so to keep it simple, I'd like to keep it as a perl one-liner. Also, for the second replacement, it could be pretty much any IP address or hostname; I'd rather not go through all my systems to build a regexp of all the possible values.

Any thoughts on how to write the second regexp?

-- Burvil

Replies are listed 'Best First'.
Re: Regexp to exclude one IP and get all others?
by moritz (Cardinal) on Apr 15, 2010 at 19:08 UTC
    but I'm not sure how to write the regexp for the second without removing lines for 127.127.1.0.

    Just write a regex that's agnostic to the specific IP address, and then a bit of Perl code that checks if the IP address is 127.127.1.0, and if not, performs the substitution.

    Perl 6 - links to (nearly) everything that is Perl 6.
Re: Regexp to exclude one IP and get all others?
by kennethk (Abbot) on Apr 15, 2010 at 19:25 UTC
    So you want something that will match server another-ip-or-hostname-here [burst iburst] for all values of another-ip-or-hostname-here except 127.127.1.0 and doesn't match if the line includes prefer, wiping the line on match? You can accomplish this fairly easily with negative look-ahead assertions.

    perl -p -i -e 's/server (?!\Q127.127.1.0\E)[\w\.]+\s+(?!prefer).*//g' ntp.conf

    See perlretut for more info. And might I suggest -i.bak in place of -i?

      Thanks. That works. :)

      -- Burvil