You need to define what you mean by your default IP address. Essentially the hosts file on Win32 typically contains just an entry for localhost. If this is all you have, plus another IP then all you need to do is overwrite the old hosts file with new data, rather than mess around with finding one IP and replacing it.

my $hosts = "C:/windows/system32/drivers/etc/hosts"; print "Line to add to hosts (x.x.x.x domain.com): "; my $line = <STDIN>; rename( $hosts, "$hosts.old" ); # effectively make backup open FILE, ">$hosts" or die "Can't write $hosts $!\n"; print FILE "127.0.0.1 localhost\n$line"; close FILE;

If you actually want to find a line and replace it the approach is a little different.

my $hosts = "C:/windows/system32/drivers/etc/hosts"; print "Line to add to hosts (x.x.x.x domain.com): "; my $line = <STDIN>; print "IP to replace: "; chomp( my $ip = <STDIN> ); rename( $hosts, "$hosts.old" ); open IN, "$hosts.old" or die "Can't read $hosts.old $!\n"; open OUT, ">$hosts" or die "Can't write $hosts $!\n"; while (my $old = <IN>) { print OUT $old unless $old =~ m/\Q$ip/; } print OUT $line; # add the new record close IN; close OUT;

If you just want to change the IP then you need to get the old ip and new ip in like at the start (remember to chomp input to remove newline). Within the loop you would just do:

$old =~ s/\Q$old_ip\s+/$new_ip /; print OUT $old;

and drop the print after the loop.

You can do it in a one liner. This particular syntax can come in very handy:

C:\>perl -pi.bak -e "s/this/that/g" <file>

This makes a backup called file.bak and replaces all instances of this with that in the original


In reply to Re: update winxp hosts file with new IP address by tachyon-II
in thread update winxp hosts file with new IP address by notasaint

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.