#! perl.exe -w # Perl Script to change format of Unigen .csv files from version 17 to + version 24. # This script will add two lines to the beginning of each file to acco +modate ARAMS Access Database # and copy the file to a final directory destination. use File::Copy; $indir = "c:/public/conversion"; $outdir = "c:/public/final"; opendir DH,$indir or die "Cannot open $indir: $!"; ## has all the files and directories in the given ## directory. You'll want to screen it to make sure you're ## opening a file. foreach $file(readdir DH) { $name = $file; next if $name =~ /^\./; # skip over dot files &addheader($_); } close DH; sub addheader { open FH, "< $indir/$file" or printf "can't open %s\n",$file; $line = <FH>; $_ = $line; close FH; $field1 = m/^Clock/; # Check for C +lock at beginning of file printf "\n$file"; if ( $field1 == "1"){ printf "\tv17\tFile Needs Appending\n"; open FH1, "< $indir/$file" or printf "can't open %s\n", $file; + # Open source file 1 while <FH1>; my $count = $.; # Gets the tota +l number of lines in file close FH1; open FH1, "< $indir/$file" or printf "can't open %s\n", $file; + my $line=<FH1>; $.= 1; my $number = 2; # Gets beginnin +g of file timestamp - fourth line from the beginning of the file print "$file\n"; do {$line =<FH1>} until $. == ($number); my @fields = parse_csv($line); print "$fields[0]\n"; my $start = $fields[0]; do {$line =<FH1>} until $. == ($count); # Get +end of file timestamp - last line @fields1 = parse_csv($line); my $end = $fields1[0]; close FH1; open FH1, "< $indir/$file" or printf "can't open %s\n", $file; + open FH2, '> c:/public/final/tmp.csv' or die "can't append: $! +" ; # Open target file - create if not there already print FH2 "PREPEND LINE1\n"; # Prepend + text print FH2 "blank,"."blank,"."blank,"."$start,"."$end\n"; + # Prepend first & last timestamp my @lines = <FH1>; foreach $line ( @lines ) # Append tmp f +ile with original files { print FH2 $line; } close FH1; close FH2; $oldfile = 'c:/public/final/tmp.csv'; $newfile = "$outdir/$file"; rename $oldfile,$newfile or die"can't rename files\n"; + # Rename tmp file to original filename print "$oldfile\n"; } else { printf "\tv24\tFile Does Not Need Appending\n"; copy "$indir/$file", "$outdir/$file"; } return ; } sub parse_csv { my $text = shift; my @new = (); push(@new, $+) while $text =~ m{"([^\"\\]*(?:\\.[^\"\\]*)*)",? | ( +[^,]+),?| ,}gx; push(@new, undef) if substr ($text, -1,1) eq ','; return @new; #list of values that were comma-seperated }
janitored by ybiC: balanced <readmore> tages around code
In reply to Style Comments by mgolini
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |