I have a huge text file that look like this: 2013/255-12:23:34 - Some event happ
ID: 3542230 • Letter: I
Question
I have a huge text file that look like this:
2013/255-12:23:34 - Some event happen
2013/255-12:23:34 - Some event happen
2013/255-12:23:34 - Some event happen
2013/255-12:23:34 - Some event happen
***Connection Lost
2013/256-12:23:34 - Some event happen
2013/256-12:23:34 - Some event happen
2013/256-12:23:34 - Some event happen
2013/256-12:23:34 - Some event happen
2013/257-12:23:34 - Some event happen
2013/257-12:23:34 - Some event happen
I would like to use perl to split this file into smaller files with the date as file name.
So I would look like this when done:
2013_255.txt will contain:
2013/255-12:23:34 - Some event happen
2013/255-12:23:34 - Some event happen
2013/255-12:23:34 - Some event happen
2013/255-12:23:34 - Some event happen
** Connection Lost
2013_256.txt will contain:
2013/256-12:23:34 - Some event happen
2013/256-12:23:34 - Some event happen
2013/256-12:23:34 - Some event happen
2013_257.txt will contain:
2013/257-12:23:34 - Some event happen
2013/257-12:23:34 - Some event happen
Thanks,
Explanation / Answer
#!/usr/bin/perl use File::Basename; $inputfile=@ARGV[0]; $nof=@ARGV[1]; # nof - no of files to split ($filename,$dir,$ext) = fileparse($inputfile,'..*'); $header=`cat $inputfile | head -1`; $NOLIF=`cat $inputfile | wc -l`; # NOLIF - no of lines in file $NOARIF=$NOLIF-1; # NOARIF - no of actual records in file $NORPF=$NOARIF/$not; # NORPF - no of records per file $NNORPF=`printf "%1.f " $NORPF`; # NNORPF - new no of records per file $count=0; $filenum=0; while () { if ( $count == 0 ) { $nfilename = $filename._.$filenum.$ext; open( FILE, ">> $nfilename" ); print( FILE "$header " ); print( FILE "$_" ); $count++; #} elsif ( $count == $NUM_LINES ) { } elsif ( $count == $NNORPF ) { close( FILE ); $count = 0; $file_num++; } else { # just write the line! print( FILE "$_" ); $count++; } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.