Operating System - HP-UX
1755703 Members
5073 Online
108837 Solutions
New Discussion юеВ

Re: perl hack: commenting lines between two markers?

 
SOLVED
Go to solution
Doug O'Leary
Honored Contributor

perl hack: commenting lines between two markers?

Hey;

I'm having a hard time wrapping my mind around this one this morning; maybe under-caffeinated..

I have a text file with two markers between which I want to be able to comment (or uncomment) lines.

I've got a beginning:

#!/usr/bin/perl
use strict;
my @lines = <>; my $lines = join*('',@lines);
my ($chunk) = $lines =~ m{^# mcsg_begins\n(.*?)#mcsg_ends}mgs;
$chunk =~ s/^/# /mg;
print $chunk;

That comments out the lines between the markers but only in the variable $chunk; I can't, for instance, print out $lines and have the stanza commented.

Anyone have a slick way of doing this? Extra helping of eternal gratitude if there's a way to do it with a perl one-liner...

Thanks for any hints/tips/suggestions.

Doug O'Leary

------
Senior UNIX Admin
O'Leary Computers Inc
linkedin: http://www.linkedin.com/dkoleary
Resume: http://www.olearycomputers.com/resume.html
3 REPLIES 3
James R. Ferguson
Acclaimed Contributor

Re: perl hack: commenting lines between two markers?

Hi Doug:

# perl -pe 's/^(.)/#$1/ if (/mcsg_begins/../mcsg_ends/)' myfile

...where:

# cat myfile
line-1
line-2
line-3
mcsg_begins
line-1.1
line-2.1
line-3.1
mcsg_ends
line-4
line-5
line-6

...yielding:

line-1
line-2
line-3
#mcsg_begins
#line-1.1
#line-2.1
#line-3.1
#mcsg_ends
line-4
line-5
line-6

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor
Solution

Re: perl hack: commenting lines between two markers?

Hi (again) Doug:

I'm under-caffeinated too. We don't need to capture in our substitution, just do:

# perl -pe 's/^/#/ if (/mcsg_begins/../mcsg_ends/)' file

Regards!

...JRF...
Doug O'Leary
Honored Contributor

Re: perl hack: commenting lines between two markers?

Outstanding! I knew there was a better way to do that than what I was coming up with!

Thanks alot!

Doug

------
Senior UNIX Admin
O'Leary Computers Inc
linkedin: http://www.linkedin.com/dkoleary
Resume: http://www.olearycomputers.com/resume.html