Perl Script - Print Content of next line

Good evening to you all perl experts

I need your help

I have a very simple script where I�m trying to print a line from status.dat file.

The script will find the line containing "servicestatus", and I want to print the content of the next line.

For example, the file contains this text:

servicestatus {
hostname = Obelix

What i want to print is "hostname = Obelix"

Could you help?

Here goes the code. I want to replace "PRINT LINE AFTER THAT" with the necessary code to print the second line after "servicestatus."

#!/usr/bin/perl -w
 

 open my $logfile, 'status.dat' or die "I couldn't get at status.dat:  $!";
 

 for my $line (<$logfile>) {
      if $line =~ /^servicestatus/;
        "PRINT LINE AFTER THAT"
}

Try:

#!/usr/bin/perl
use warnings;
use strict;

open (LOG,"<","status.dat") or die "I couldn't get at status.dat:  $!";

while (<LOG>) {
        chomp ($_);
        if ($_ =~ /^servicestatus/){
                my $nextline=<LOG>;
                print "$nextline";
        }
}

You could try:

#!/usr/bin/perl -w
open LOGFILE, 'status.dat' or die "I couldn't get at status.dat:  $!";
while (<LOGFILE>) {
  print $_=<LOGFILE> if /^servicestatus/
}

And yet another way:

$
$ cat t1
servicestatus {
hostname = Obelix
blah blah
}
servicestatus {
hostname = Asterix
blah blah
}
servicestatus {
hostname = Getafix
blah blah
}
$
$ perl -lne 'BEGIN{undef $/} while (/servicestatus {\n([^\n]+)\n/g){print $1}' t1
hostname = Obelix
hostname = Asterix
hostname = Getafix
$
$

tyler_durden

That's almost like awk :slight_smile:

awk '/^servicestatus/{getline;print}' infile

It worked...thankx to you all...you guys rulle!

---------- Post updated at 06:09 AM ---------- Previous update was at 04:22 AM ----------

Btw, one more doubt...

Do you know how I can get the previous line instead of the next one?

Imagine that I have the following:

servicestatus {
hostname = Obelix
service name = test

The script will find the line containing "service name = test", and I want to print the content of the previous line "hostname = Obelix".

---------- Post updated at 08:10 AM ---------- Previous update was at 06:09 AM ----------

Ok...i got it

Here�s one getting the previous line:

#!/usr/bin/perl -w

open (CHECKLOG, "status.dat");

@LINHAS = <CHECKLOG>;
@lnumber = @LINHAS;
$lnumber = @lnumber;

for ($i=0;$i < $lnumber; $i++){
        if($LINHAS[$i] =~ /^\tservice_description=PING/){
                print "Linhas: $LINHAS[$i-1]\n";
        }
}

Thkx again to you experts :wink:

#!/usr/bin/perl -w
open LOGFILE, 'status.dat' or die "I couldn't get at status.dat:  $!";
while (<LOGFILE>) {
  print $prev if /^service name = test/;
  $prev=$_
}