Hello Endurance,
I hope you are doing well and you have become a Perl expert by now. ;-) I was looking for something here on PerlMonks (I use the search function quite a lot), and I stumbled upon this post by accident. For sake of future visitors and people who use to search for answers, I thought I would make a few hints.
When you're dealing with a relatively small file, then it's okay to read the entire file into memory. Next, you can split it so it occupies an array where each line is stored in an array element. I split it like this:
my @ARRAY = split(/[\r\n]+/, $ENTIRE_FILE_CONTENT);
Now, let's create a for loop that prints each line, so you can see how we can access each line in the array:
for (my $i = 0; $i < @ARRAY; $i++) { print "\n$ARRAY[$i];"; }
The current line is $ARRAY[$i], and to access the 3rd line from here, you would do that by writing $ARRAY[$i + 3]
The problem is if you reach the end of the array, then addressing the 3rd line from the last does not exist. So, you could get an error! To fix that, you could either check each time to make sure the array has enough elements:
for (my $i = 0; $i < @ARRAY; $i++) { if ($i + 3 < @ARRAY) { print "\n$ARRAY[$i + 3]"; } }
OR you could just set up the for loop so it skips the last 3 lines. That way you don't have to worry about checking each time:
my $STOP = @ARRAY - 3; for (my $i = 0; $i < $STOP; $i++) { print "\n$ARRAY[$i + 3]"; }
Now, when you want to search for a line, you should know whether you want to search for a text that occurs anywhere in the line OR if the requirement is that you have to find a line that matches EXACTLY what you are looking for.
To find whether a string occurs in the line, I would use the index() function:
my $FOUND = index($ARRAY[$i], 'solar winds'); if ($FOUND >= 0) { print "\nFOUND SOLAR WINDS IN LINE $i"; }
To see if a line precisely matches a certain string, use the eq operator:
if ($ARRAY[$i] eq 'solar winds') { print "\nLINE $i MATCHES SOLAR WIND +S"; }
So, let's put this together now!
my $STOP = @ARRAY - 3; for (my $i = 0; $i < $STOP; $i++) { if (index($ARRAY[$i], 'solar winds') >= 0) { $ARRAY[$i + 3] =~ s/country/place/; } # Use a regex to replace c +ountry... }
2023-04-03 Athanasius fixed code formatting.
In reply to Re: Edit lines from a file and replace multiple lines.
by harangzsolt33
in thread Edit lines from a file and replace multiple lines.
by Endurance
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |