Reputation: 13
I am trying to take a file, and copy it to an output file and then find all the <k>
and make them into <p>
instead. I want to use regex.
while (<INPUTFILE>)
{
if($_ != "<p>")
{
print OUTPUTFILE "$_\n";
}
else
{
print OUTPUTFILE "<k>";
}
}
I was trying something like this but I guess the $_ variable takes each line at a time. So It would prob be better to use write the entire file then try the regex search and replace? for that I have tried:
$_ =~ s/<k>/<p>/g;
Upvotes: 1
Views: 211
Reputation: 185881
If you really want to treat the whole file in one time :
BEGIN { $/ = undef; $\ = undef; }
LINE: while (defined($_ = <ARGV>)) {
s/<k>/<p>/g;
print $_;
}
From :
perl -0777 -MO=Deparse -pe 's/<k>/<p>/g; print;'
Upvotes: 0
Reputation: 5093
From the command line
perl -pe 's/<k>/<p>/g' <infile >outfile
Simples.... :-)
Look up 'change record separator' if you are concerned about newline effects
Upvotes: 0
Reputation: 7143
As @ikegami suggests, one line at a time is no problem. Alternatively, you could do this in a single search and replace:
{
local $/ = undef;
my $data = <INPUTFILE>;
$data =~ s/<k>/<p>/g;
}
This would do the search and replace in a single operation and might be faster and/or more efficient for larger files.
Upvotes: 1
Reputation: 386706
A line at a time is not a problem.
while (<>)
s/<k>/<p>/g;
print;
}
Upvotes: 5