0

I have some text file which have data in the following format:

Summary:
xyz

Configuration:
abc
123

Tools:
pqr
456

The tags 'Summary:', 'Configuration:' and 'Tools:' remain the same for all the files and just the content below that changes. I need to extract just the content from the text file and print it out.

Thanks.

4 Answers 4

1
use strict;
use warnings;

my (%h, $header);
while (<>) {
    if (/^(\w+):) { 
        $header = $1; 
    } elsif (defined $header) { 
        push @{$h{header}}, $_; }
}
print Dumper \%h;

If your non-header lines can contain :, you may need something stricter, such as:

if (/^(Summary|Configuration|Tools):/)
Sign up to request clarification or add additional context in comments.

Comments

1

How about something like:

open(FH, '<myfile.txt');
while(<FH>)
{
  print $_ unless /Summary:|Configuration:|Tools:/;
}

You'll have to cleanup the regex a bit, but that should do it.

1 Comment

Thank you. As you said needed a bit of cleanup, but gave me the idea
0

Not sure if you have one file or many, but if the former case:

Summary: xyz

Configuration: abc 123

Tools: pqr 456

Summary: xyzxyz

Configuration: abcd 1234

Tools: pqr 457

You can use something like the following to print all configuration lines:

#!/usr/bin/env perl

open (FILE, 'data.txt') or die "$!";

while (<FILE>) {
    if (m/^(Configuration):(.*)/) {
      print $2 . "\n";
    }
}
close FILE;

Change the regex if you want other lines or to m/^(Configuration|Tools|Summary):(.*)/ for all of them.

Comments

-1

Or the considerably less elegant

#!/usr/bin/perl
my $fi;
my $line;
my @arr;
open($fi, "< tester.txt") or die "$!";

while ($line = <$fi>) 
{
    if (!($line =~ /:/))
    {
        push(@arr, $line);
    }
}

foreach (@arr)
{
    print $_;
}

close ($fi);
close ($fo);

2 Comments

please don't answer old posts with something considerably less elegant
Hmmm... I was thinking about how perl-golfed one liners are not always intuitive to newer Perl people. But meh I'm eternally a noob, or I would have noticed how old this is, heh.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.