我有一个 file.txt,其中包含如下数据:
word = blabla
a = 1
b = 2
c = 3
word = blabla_b
a = 11
b = 22
c = 33
(基本上,这个文件是由一个java代码创建的,它将“a”包含的数字写入这个文件,然后在某个循环中的“b”和“c”之后,显然a,b,c 1,2,3只是一个例子,我有不同的名字和不同的数字:-))
我需要做的是:
- 从 CMD 提供的文件中读取
- 将其写入 CSV 文件(由 excel 打开)并在每列的底部(“word”除外,因为它不是数字)以获得平均值:(我知道如何在 excel 文件中计算平均值,但我想要脚本自行完成)
最后应该是这样的:
我做了一些不通用的事情,但它非常愚蠢,我相信可能会有更优雅的方式!
my $in_file = shift;
my $fileName = "CSV_file";
open $out_file, ">$fileName.csv" or die "can't open $fileName: $!";
my @fields = ("word","a","b","c");
foreach (@fields)
{
#first write down the line of the headlines per each column
print $out_file "$_,";
}
print $out_file "\n";
open STATS, "<$in_file" or die "Error opening file \$in_file";
local($counter) = 0;
#creating avg and sum variables for each column - not clever once i'll have much more columns!!!!!!!!!
my $avgA = 0 , $avgB = 0 ,$avgC = 0;
my $sumA = 0 , $sumB = 0 ,$sumC = 0;
my $numOfRows = 0;
while (<STATS>)
{
chop;
($name, $number) = split("=");
print $out_file "$number";
if ($counter == $#fields) #end of row
{
print $out_file "\n";
$sumC += $number;
$counter = 0;
$numOfRows++;
}
else
{
print $out_file ",";
$counter++;
}
#adding to the Sum of each column (in order for future Avg calc)
if ($counter == 2)
{
$sumA += $number;
}
elsif ($counter == 3)
{
$sumB += $number;
}
}
$avgA = $sumA/$numOfRows;
$avgB = $sumB/$numOfRows;
$avgC = $sumC/$numOfRows;
print $out_file "AVG:,$avgA ,$avgB,$avgC \n";
close (FILE);