This example will use the last directory as the label, so it is not limited to using just BAKERY or FRUITJUNCTION and it won't break if those patterns occur elsewhere in the path (see the last two example paths).
Output:use strict; use warnings; # for portable path and filename operations use File::Spec; my @paths = qw( /home/units/bakery/cake.pl /home/units/bakery/pie.pl /home/units/bakery/plumcake.pl /home/units/fruitjunction/juice.pl /home/units/fruitjunction/icecream.pl /home/units/bakery/choclate.pl /home/bakery/fruitjunction/not_a_bakery.pl /home/units/foo/bar.pl ); my $current_dir = ''; foreach my $path ( @paths ) { chomp $path; # retrieve the last directory in the path my $dir = get_dir( $path ); # print a start label if this is the first path if( $current_dir eq '' ) { $current_dir = uc( $dir ); print "# $current_dir\n"; } # change labels if required if( uc( $dir ) ne $current_dir ) { print "# END $current_dir\n"; $current_dir = uc( $dir ); print "# $current_dir\n"; } print "$path\n"; } print "# END $current_dir\n"; sub get_dir { my ( $path ) = @_; # extract the directory portion of the path my ( undef, $dirs, undef ) = File::Spec->splitpath( $path ); # remove trailing directory separators $dirs = File::Spec->canonpath( $dirs ); # split the path on directory separators my @dir = File::Spec->splitdir( $dirs ); return $dir[-1]; }
# BAKERY /home/units/bakery/cake.pl /home/units/bakery/pie.pl /home/units/bakery/plumcake.pl # END BAKERY # FRUITJUNCTION /home/units/fruitjunction/juice.pl /home/units/fruitjunction/icecream.pl # END FRUITJUNCTION # BAKERY /home/units/bakery/choclate.pl # END BAKERY # FRUITJUNCTION /home/bakery/fruitjunction/not_a_bakery.pl # END FRUITJUNCTION # FOO /home/units/foo/bar.pl # END FOO
In reply to Re: insert lines based on some pattern
by bobf
in thread insert lines based on some pattern
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |