简体   繁体   中英

Perl regex replace

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;

A line at a time is not a problem.

while (<>)
   s/<k>/<p>/g;
   print;
}

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.

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;'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM