0

y.txt -> file to be edited x.txt -> file that needs to be copied and written in y.txt

y.txt has

c...
w...
// search for this comment and copy the entire x.txt file here 
// search end comment when you need to delete lines between these comments
g...

How do I do this in Perl? Also how do I search for both the comments and delete the lines between them?

So y.txt looks like this after insertion

c...
w...
// search for this comment and copy the entire x.txt file here 
Entire x.txt file here
// search end comment when you need to delete lines between these comments
g...

The file to be inserted is about 20 lines in total. I create this file as well.

Zazy
  • 47
  • 6

1 Answers1

2

Here is one approach:

use strict;
use warnings;

my $xfn = 'x.txt';
open ( my $fh, '<', $xfn ) or die "Could not open file '$xfn': $!";
my $xstr = my $str = do { local $/; <$fh> };
close $fh;
@ARGV = qw(y.txt);
$^I = '.bak';  # Backup file extension
my $delete = 0;
while(<<>>) {
   if (m{// search end comment}) {
      $delete = 0;
   }
   next if $delete;
   print;
   if (m{// search for this comment}) {
      $delete = 1;
      print $xstr;
   }
}
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
  • Thanks! How to delete just between the comments and not the entire file before replacing it? – Zazy Apr 04 '21 at 21:37
  • It is actually deleting just between the comment as it is now. Maybe you can provide a link to your input files ? Then I can check what might be the problem.. – Håkon Hægland Apr 04 '21 at 21:40
  • This works well if i have no command line inputs but I have quite a few. So I am not sure how to about then. – Zazy Apr 06 '21 at 01:56
  • Oh I see that's what caused the problems.. then you should pop all items from `@ARGV` first. You may contact me by email if something is not clear. – Håkon Hægland Apr 06 '21 at 08:15