the following script text.pl (described below) define to append the $insert text between $first_line and $second_line in the file – myfile.txt
While:
$first_line=A
$second_line=B
$insert = "hello world"
for example
before test.pl running
A
B
After I run test.pl we get:
A
hello world
B
the problem: but if there line space between A line and B line then it doesn’t append the “hello world” as the following , what need to change in the script in order to append the $insert param also if I have in the file space line between A to B ?
A
B
test.pl script
use strict;
use warnings;
# Slurp file myfile.txt into a single string
open(FILE,"myfile.txt") || die "Can't open file: $!";
undef $/;
my $file = <FILE>;
# Set strings to find and insert
my $first_line = "A";
my $second_line = "B";
my $insert = "hello world";
# Insert our text
$file =~ s/\Q$first_line\E\n\Q$second_line\E/$first_line\n$insert\n$second_line/;
# Write output to output.txt
open(OUTPUT,">output.txt") || die "Can't open file: $!";
print OUTPUT $file;
close(OUTPUT);
This would replace everything between Line 1 and 2 (even nothing) by insert:
Edit/Addendum
After reading your “enhanced specification”, its much clearer how to solve this. You include the Start (^) and End ($) of the lines into the regular expression. In order to keep this maintainable, I did take out the expression and made a variable of it. I tested it and it seems to work (even with ‘(‘) and stuff):
I created such a file:
and it got inserted properly.
Regards
rbo