G'day bowei_99,
Here's a solution using Tie::File you may find suitable.
#!/usr/bin/env perl use strict; use warnings; use Tie::File; my $file = 'pm_file_insert_re.file'; my $re = qr{ \A echo .* install_list \z }x; my $insert_line = 'echo ":app:new-name-here:" >> /mnt/install_list'; tie my @lines, 'Tie::File', $file or die "Can't tie $file: $!"; my $last_found = 0; @lines = reverse map { /$re/ && ! $last_found++ ? ($insert_line, $_) : $_ } reverse @lines; untie @lines;
Here's a run showing before and after file contents.
ken@ganymede: ~/tmp $ cat pm_file_insert_re.file early text echo ":os:5.7:" >> /mnt/install_list middle text echo ":app:name-here:" >> /mnt/install_list later text ken@ganymede: ~/tmp $ pm_file_insert_re.pl ken@ganymede: ~/tmp $ cat pm_file_insert_re.file early text echo ":os:5.7:" >> /mnt/install_list middle text echo ":app:name-here:" >> /mnt/install_list echo ":app:new-name-here:" >> /mnt/install_list later text ken@ganymede: ~/tmp $
-- Ken
In reply to Re: Look Ahead regexp to insert line?
by kcott
in thread Look Ahead regexp to insert line?
by bowei_99
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |