How to merge the contents of Multiple files stored in the Hash and generate the merged file output along with Header in tabular form
For example, i have 2 files (File1.txt and File2.txt) and generate the present the output with Header Information as below
I was able to present the merged file but without header information :(
Header information i am missing to put is "Distance Fuel_Consumption_Curr Fuel_Consumption_Baseline1" in the output generated as files will get processed
Monks Please help...
Your help in understanding the logic will be greatly appreciated
1. Current_results (File1.txt): Distance Fuel_Consumption 60 2.0 80 2.2 100 3.0 200 5.5 <EOF> 2. Baseline1 (File2.txt): Distance Fuel_Consumption 60 1.0 80 1.5 100 2.3 200 4.2 <EOF> 3. Output (Report.txt) Distance Fuel_Consumption_Curr Fuel_Consumption_Baseline1 60 2.0 1.0 80 2.2 1.5 100 3.0 2.3 200 5.5 4.2 <EOF>
Code written to process the files
#!/usr/bin/perl -w use strict; use Data::Dumper qw(Dumper); my @list_of_files = qw(file1.txt file2.txt); my %data; my $file_num = 0; my $Distance; foreach my $file_name (@list_of_files) { $file_num++; my $file = 'File'.$file_num; my $flag = 0; open FH, $file_name or die "Cannot open $file_name. $!"; while(<FH>){ chomp; if($_ =~ /\s*(\d+)\s*(\d+\.\d+)/){ $Distance=$1; $data{$Distance}{$file}{'Fuel_Consumption'}=$2; next; } } close FH; } print Dumper(\%data); my ($tmpDist,$tmpFile,$tempValue); print "Merged output\n"; foreach $tmpDist (sort{ $a <=> $b } keys( %data ) ) { print "$tmpDist"; foreach $tmpFile (sort{ lc($a) cmp lc($b) } keys( %{$data{$tmpDist +}} ) ) { $tempValue=$data{$tmpDist}{$tmpFile}{'Fuel_Consumption'}; print "\t $tempValue"; } print "\n"; }
Output generated is as follows but without header information is as follows
Header missing is : Distance Fuel_Consumption_Curr Fuel_Consumption_Baseline1
60 2.0 1.0 80 2.2 1.5 100 3.0 2.3 200 5.5 4.2
In reply to How to merge the contents of Multiple files stored in the Hash and generate the merged file output along with Header in tabular form by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |