-2

i have one file which contain following info - input -

a[1]= something_data_1;
a[2]= something_data_2;
a[3]= something_data_3;

so i want to replace that "a" with different pattern like below, Here diff* is a string which I want to replace.

Output -

diff1 [1]= something_data_1;
diff2 [1]= something_data_1;
diff3 [1]= something_data_1;

diff1 [2]= something_data_2;
diff2 [2]= something_data_2;
diff3 [2]= something_data_2;

.....

I have tried:

/usr/bin/perl -w

open(FH,'<',$file_name);
 foreach(<FH>)
  {
    if(/a(\[.*)/)
    {
      $_= "diff1$1 ". "diff2$1";
    }
  }

after trying this i am getting output like this,

diff[1] = diff2 something_data;

i am not able to understand what to do

closed as unclear what you're asking by peterh, RalfFriedl, Mr Shunz, mosvy, Jeff Schaller Jan 13 at 15:25

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • You do realize that once you replaced the "a" with "diff1" that there's no longer an "a" to replace with "diff2"? – Jeff Schaller Jan 12 at 18:33
  • Can you describe your desired transformation with some English phrases, instead of just code? Why wouldn't a static output of those 3 strings be sufficient? – Jeff Schaller Jan 13 at 15:25
  • yes jeff you are right once i replaced that a with diff1 there is no longer a to replace , is there any counter solution to get desired output mentioned above – deepak kulkarni Jan 13 at 16:35
  • Does your input file have DOS-style line endings? – glenn jackman Jan 13 at 18:11
  • its unix -style ending – deepak kulkarni Jan 13 at 18:18
1

You might want something like

chomp(my $line = $_);
if ($line eq "a") {
    $_ = "diff1\ndiff2\ndiff3\n";
}

I'm assuming you haven't chomped so that $_ still 3nds with newline. You need to capture the text that follows "a" so you can reuse it:

if (/^(\s*)a(\[.*)/) {
    $_ = "${1}diff1$2".
         "${1}diff2$2".
         "${1}diff3$2;
}
  • Hi glenn can you please help for edited question,thanks in advance. – deepak kulkarni Jan 13 at 8:53
  • hi glen , using your solution i am getting output something like this, diff1[1] =diff[2] = something; – deepak kulkarni Jan 13 at 16:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.