Join Function in PERL

Hi,

Can any one please let me know, how to join the lines in a file, but based one a condition.

There is a file, where few lines start with a date stamp. and few do not.

I wanted to join the lines till I find a date stamp. If found date its should in a newline.

Please help me.

Thanks in Advance

perl -ne 'chomp;if (/TIMESTAMP/){$_="\n" . $_;$\="\n";}print;' in.file > out.file

Hey bartus11

I tried as below with the code you gave, but it dint worked can you please let me know where am doing a mistake.

#!/usr/bin/perl
use strict;
my $dt=`date +%Y-%m-%d`;
chomp $dt;

my $inp_file=""/home/skMessages.log";

{
chomp $inp_file;
open (INFILE,"$inp_file") || die "Cant open $inp_file for reading ";

    while \(<INFILE>\)
    \{
            if \($_ =~ $dt\)
            \{
                    $_="\\n" . $_;$\\="\\n";
                    print;
            \}
    \}

}
close(INFILE);

---------- Post updated at 11:55 AM ---------- Previous update was at 11:53 AM ----------

#!/usr/bin/perl
use strict;
my $dt=`date +%Y-%m-%d`;
chomp $dt;
 
my $inp_file=""/home/skMessages.log";
 
{
chomp $inp_file;
open (INFILE,"$inp_file") || die "Cant open $inp_file for reading ";
 
while (<INFILE>)
{
if ($_ =~ $dt)
{
$_="\n" . $_;$\="\n";
print;
}
}
}
close(INFILE);
#!/usr/bin/perl
use strict;
my $dt=`date +%Y-%m-%d`;
chomp $dt;
my $inp_file="/home/skMessages.log";
open (INFILE,"$inp_file") || die "Cant open $inp_file for reading ";
while (chomp ($_=<INFILE>)){
  if ($_ =~ $dt){
    $_="\n" . $_;
    $\="\n";
  }
  print;
}
close(INFILE);
1 Like

Its printing in a same line, all the file, the joining is not breaked if found date stamp.

2009-11-10 04:49:16,170 INFO handlers
b;
c;
ddaa;

2009-11-10 04:49:16,170 INFO handlers
aa;
bb;
cc;

OUTPUT:

2009-11-10 04:49:16,170 INFO handlers b; c; ddaa;
2009-11-10 04:49:16,170 INFO handlers aa; bb; cc;

Sorry for the confusion, if any.

Thanks

Something like this maybe ?

$
$
$ cat f1
2009-11-10 04:49:16,170 INFO handlers
b;
c;
ddaa;

2009-11-10 04:49:16,170 INFO handlers
aa;
bb;
cc;
$
$
$ perl -ne 'chomp; if (/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d,.*$/ or /./){print $_," "} else {print "\n"} END {print "\n"}' f1
2009-11-10 04:49:16,170 INFO handlers b; c; ddaa;
2009-11-10 04:49:16,170 INFO handlers aa; bb; cc;
$
$

tyler_durden