perl extract information from several files in folders into the specific files -
i'm trying extract of daily data analyze yearly something.
so, made code searching folder , files.
after wanna extract curtain lines in several files has same name in middle.
when done work, realize there 1 day information left
daily data grid format this.
ncols 751 nrows 601 xllcorner 124.5 yllcorner 33. cellsize 0.01 nodata_value -99 -99.0 -99.0 -99.0 -99.0 -99.0
i wanna result code.
1.txt (2011) 10 10 10 10 10 4 4 3 2 5 4 3 2 10 4 4 3 2 1 1 10 10 10 10 10 10 2.txt (2012) 3 4 2 10 10 4 4 3 2 5 4 3 2 10 4 4 3 2 1 1 10 10 10 10 10 10
use 5.010; use warnings; if( $#argv < 0 ) { die "need folder.\n"; } $dirname = shift(@argv); local($i); #rutine &readsubdir($dirname); sub readsubdir { if(!opendir(dirhandle, $_[0])) { print "$_[0] failed opening.\n"; return 0; } local(@files) = readdir(dirhandle); local($i); local($newfile); local(@dironly); local(@fileonly); for($i = 0; $i <= $#files; $i++) { $newfile = $_[0]."\\".$files[$i]; if(-d $newfile) { push(@dironly, $files[$i]); } elsif(-f $newfile) { push(@fileonly, $files[$i]); } else {} } @files = @dironly; push(@files, @fileonly); closedir dirhandle; $cnt = 1; $b = 2011; for($i =0; $i <= $#files; $i++){ $newfile = $_[0]."\\".$files[$i]; if(-f $newfile){ open(filehandle, $newfile)|| die "cannot open 개체 \n"; my($dir, $file, $ext) = ($newfile =~ m|^(.*\\)(.*)(\..*)$| ); if (substr($file,17,4) eq $b){ while(<filehandle>){ if($. == 7){ $filename = $cnt.'.txt'; open out, ">$filename" or die "failed create $filename"; print out $_; } } close(filehandle); } elsif (substr($file,17,4) eq $b+1){ $b++; $cnt++; while(<filehandle>){ if($. == 7){ $filename = $cnt.'.txt'; open out, ">$filename" or die "failed create $filename"; print out $_; } } close(filehandle); } } close(out); } }
the question isn't clear you're trying accomplish, information in daily file data example doesn't match of data in output examples. however, looking @ code think you're trying , think problem occurring when open output file store lines extracted. you're opening file >, indicates you're opening file output, overwrite file if exists. code overwriting same file on , on , information in last file saved. need open file in append mode using >>. code should similar following:
open out, ">>$filename" or die "failed create $filename";
Comments
Post a Comment