Kerby82
Kerby82

Reputation: 5146

How do I substitute a particular IP in a file with Perl?

I have a list of IPs, I have to transform all the lPs starting with 210.x.x.x to 10.x.x.x

For example:

210.10.10.217.170 ----> 10.10.10.217.170

Is there any in-line Perl regular expression substitution to do that?

I would like to have this substitution in Perl.

Upvotes: 2

Views: 183

Answers (4)

Eugene Yarmash
Eugene Yarmash

Reputation: 149776

You could use perl -pe to iterate over the lines of the file and do a simple substitution:

perl -pe 's/^210\./10./' file

Or to modify the file in-place:

perl -pi -e 's/^210\./10./' file

See perlrun and s///.

Upvotes: 1

kurotsuki
kurotsuki

Reputation: 4777

# Read the IP list file and store in an array
$ipfile = 'ipfile.txt';
open(ipfile) or die "Can't open the file";
@iplist = <ipfile>;
close(ipfile);

# Substitute 210.x IPs and store all IPs into a new array
foreach $_(@iplist)
{
  s/^210\./10\./g;
  push (@newip,$_);
}

# Print the new array
print @newip;

Upvotes: 1

Sean Bright
Sean Bright

Reputation: 120644

$ip =~ s/^210\./10./;

Upvotes: 3

OMG_peanuts
OMG_peanuts

Reputation: 1817

why don't you use sed instead ?

sed -e 's/^210\./10./' yourfile.txt

If you really want a perl script :

while (<>) { $_ =~ s/^210\./10./; print }

Upvotes: 2

Related Questions