Hi there,
I've an input file as follows:
*START
1001 a1
1002 a2
1003 a3
1004 a4
*END
*START
1001 b1
1002 b2
1004 b4
*END
*START
1001 c1
1004 c4
*END
I would like to split this file into three files such that the contents of first file contains all the rows between the first set of *START and *END, the contents of the second file contains the rows between the second set of *START and *END and so on.
My output will be three files:
file1
1001 a1
1002 a2
1003 a3
1004 a4
file2
1001 b1
1002 b2
1004 b4
file3
1001 c1
1004 c4
Any assistance is greatly appreciated.
$
$ cat kbirde.txt
*START
1001 a1
1002 a2
1003 a3
1004 a4
*END
*START
1001 b1
1002 b2
1004 b4
*END
*START
1001 c1
1004 c4
*END
$
$ perl -ne 'BEGIN {$/=""; $i=1;}
> {
> while (/\*START.(.*?)\*END/gs) {
> open (F,">file".$i++); print F $1; close(F);
> }
> }' kbirde.txt
$
$ cat file1
1001 a1
1002 a2
1003 a3
1004 a4
$
$ cat file2
1001 b1
1002 b2
1004 b4
$
$ cat file3
1001 c1
1004 c4
$
Hope that helps,
tyler_durden
______________________________________________
"Only after disaster can we be resurrected."
Hi Tyler,
Thanks a lot. Can this be written in awk (bash shell)?
Regards,
kbirde
Yes, sure,you can definitely use awk to do it as well.
Try this. This should create as many files as there are START and END pair
awk 'BEGIN{i=1}/\*START/{getline;n=0
while ($0 !~ /\*END/){s=(n==0) ? $0: s"\n"$0;n=i;getline}print s > "file"'"i"';
print "one over";i++
}' filename
cheers,
Devaraj Takhellambam
Hello Devaraj,
Thanks so much for the assistance.
Cheers,
kbirde
Another approach:
awk '/START/{p=1;i++;next}
/END/{p=0;next}
p{print > "file" i}' file
perl:
$/="*END\n";
open $fh,"<","a.txt";
while(<$fh>){
open FH,">file$..txt";
print FH $_;
close FH;
}
close $fh;
awk:
nawk 'BEGIN{n=1}
{
file=sprintf("%s.txt",n)
print $0 >> file
if ($0 ~ /^*END/)
n++
}
' a.txt