sam sam - 1 month ago 4
Perl Question

How to append and the line once the matched pattern is found

I want to search the string in a file and if the search string is found
then I want to replace the three line based on value in curly braces.

I was going through one of solution from stack overflow

Perl - Insert lines after a match is found in a file
is-found-in-a-file

But the things are not working for me
input_file:

abcdef1{3} { 0x55, 0x55, 0x55 }
abcdef2{2} { 0x55, 0x55}


code:

use strict;
use warnings;
my $ipfile = 'input.txt';
open my $my_fh "<", $ipfile or die "Couldn't open input file: $!";
while(<$my_fh>)
{
if (/$abcdef1/)
{
s/abcdef1{3} {\n/abcdef1{3} {\nabcdef1 0x55\nabcdef1 0x55\nabcdef1
0x55\n/gm;

}
}


expected output:

abcdef1 0x55
abcdef1 0x55
abcdef1 0x55
abcdef2 0x55
abcdef2 0x55


Any help with explanation would be grateful.

Answer

Note in perlre and RE.info that using $ and { ... } have special meanings within regular expressions. You may not see output because you are missing at least one print statement. The first curly enclosure (ie: {\d+}) could be optional unless you want to validate the length of the series in the second enclosure.

Your loop may look something like:

while (<$my_fh>) {
  if (/
      ^               # beginning of line
      ([^{]+)         # the base pattern captured in $1 ("non-left curly braces")
      .*              # any number of characters
      \{\s*(.*?)\s*\} # the data section surrounded by curlies captured in $2
      $               # end of line
      /x)          # allow whitespace and comments
  {
    for my $val (split /, /, $2) {
      print "$1 $val\n";
    }
  } else {
    print;
  }
}

Or more tersely:

while (my $line = <$my_fh>) {
  if ($line =~ /^([^{]+).*\{\s*(.*?)\s*\}$/) {
    $line = '';
    $line .= "$1 $_\n" for split /, /, $2;
  }
  print $line;
}

The ? in the pattern .*? indicates a non-greedy match. In this case, it avoids matching the whitespace next to the second right curly brace.

Comments