my $regex = "s/$old/$new/g";
On top of that, you're taking it for granted that the command line option strings really are valid IP addresses and host names, and you're putting them into a shell command that you then pass to a single-arg system() call. Personally, I'd feel better if these were checked first -- better still if you don't put the one-liner perl script on the command line at all.
In terms of simplifying things (while also fixing the problems above), you could consider something like this (untested):
That still has the potential for trouble when editing the router files, if they contain any full IP addresses where the latter three components might match the first three components of the "old" IP address. If that's really a risk, you'll need to write a special one-liner script just for them.#!/usr/bin/perl use strict; use Getopt::Long; # ... define arrays of file names, then ... my ( $opt_ip, $opt_host ); GetOptions( 'ip=s' => \$opt_ip, 'host=s' => \$opt_host ); my $Usage = "Usage: $0 [-ip old:new] [-host old:new]\n"; die $Usage unless ( $opt_ip =~ /\S:\S/ or $opt_host =~ /\S:\S/ ); my $ipreg = qr/\d{1,3}(?:\.\d{1,3}){3}/; my $hostreg = qr/\w+(?:\.\w+){2,}/; if ( $opt_ip ) { $opt_ip =~ /($ipreg):($ipreg)/ or die "Bad value for -ip: $opt_ip\ +n $Usage"; my ( $old, $new ) = ( $1, $2 ); doReplace( $old, $new, 'IP', \@ipFiles ); s/.\d+$// for ( $old, $new ); doReplace( $old, $new, 'RTR', \@routerfiles ) if ( $old ne $new ); } if ( $opt_host ) { $opt_host =~ /($hostreg):($hostreg)/ or die "Bad value for -host: +$opt_host\n $Usage"; my ( $old, $new ) = ( $1, $2 ); doReplace( $old, $new, 'HOST', \@hostFiles ); } sub doReplace { my ( $old, $new, $typ, $files ) = @_; open TMP,">/tmp/$typ-config-editor.$$.perl" or die "can't write sc +ript file: $!" print TMP "s{\\b\\Q$old\\E\\b}{$new}\n"; close TMP; for my $f ( @$files ) { my $cmd = "perl -i .bak.$$ -p /tmp/$typ-config-editor.$$.perl +$f"; print "cmd: $cmd\n"; # system( $cmd ) or print "\t $f changed\n"; # (system returns exit status of $cmd: 0 for success) } }
In reply to Re: Solaris - change hostname / ip / default-router-ip script
by graff
in thread Solaris - change hostname / ip / default-router-ip script
by Qiang
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |