Manish
Manish

Reputation: 3531

How to match multiline data in perl

This question refers to

How to replace text using greedy approach in sed?

I have to match multiline data in file and need to replace them with some other text using perl.

cat file

 <strong>ABC
       </strong>

perl script: code.pl

 #!/bin/perl
 open(fh, $ARGV[0]) or die "could not open file\n";
 while($input = <fh>)
 {
      if($input =~/&lt;strong&gt;(.*?)\n(\s)*&lt;\/strong&gt;/)
      {
          print($1,"\n");
      }
 }
 close(fh);

perl code.pl file

Output: No output

How to solve above pblm.

Regards

Upvotes: 0

Views: 1153

Answers (1)

Jeffrey Ray
Jeffrey Ray

Reputation: 1264

use File::Slurp qw( read_file );

my $string = read_file( $ARGV[0] );

$string =~ s/\&lt;strong&gt;(.*?)&lt;\/strong&gt;/<b>${1}<\/b>/gs;

print $string;

This example uses the File::Slurp module to read in the entire file at once.

It then uses a regex with the g and s modifiers. The s allows .*? to match newline characters. The g makes the search global. Global meaning it will find all matches in the given string. Without the g only the first instance would be replaced. If you want your search to be case insensitive, you can use the i regex modifier.

The ${1} is a back-reference to the match in parentheses.

This example produces:

<b>ABC
     </b>

Upvotes: 1

Related Questions