如何从文件中提取特定数字来求解方程式?

如何从文件中提取特定数字来求解方程式?

我有多个如下所示的文件:

//   copyright kkshlglkf
//   lhafslghldk
//   rsghlgsrlskl
//   sgkg
//   sgrjgrs
//   Memory:   BDRAM_SP
//   Bits:     32
//   Mux:      8
//   ladhdal:  sdj
//   zdfjhael: apfiehad
     slhgslfkghlkj
     slgdhlgfdkkdf
     Dataoutstage: None;
     TransparentMode: None;
     CellName: BDRAM_SP;
MemoryTemplate(BDRAM_SP)
{
 afljefkaf
 aslhkldfjfa
 fihhfejksgj
 dfhdhsgjshgf
 zdkjjgshgf
 sjfhfjkh
 sfdkjssjfh

我需要提取数字328然后计算结果

sum=b * (0.004+(c * 0.00008));

其中b=32c=4

结果应以 形式写入文件Result: sum;

我怎样才能实现这个目标?

答案1

您可以使用以下 perl script

#!/usr/bin/perl                                                          
use strict;
use warnings;

foreach my$file (@ARGV)
{
    open(IN,'<',$file) or die $!;
    open(OUT,'>',$file.".result") or die $!;
    my$b;
    my$c;
    my$sum;
  while(<IN>)
  {
      ($b)=$_=~/(\d+)/ if $_=~/Bits/;
      ($c)=$_=~/(\d+)/ if $_=~/Mux/;
      print OUT $_;
  }
  print STDERR "found values in ",$file,":\n";
  print STDERR "Bits: ",$b,"\nMux: ",$c,"\n";

    $sum=$b * (0.004+($c * 0.00008));
    print STDERR "writing sum (",$sum,") to the output ",$file,".result\n";
    print OUT "Result: ",$sum,";\n";

    close OUT or die $!;
    close IN or die $!;
}

它在输入文件中搜索字符串多路复用器,提取以下数字并将等式($sum=$b * (0.004+($c * 0.00008)))的结果打印到输出文件中Result: <number>;。输出文件命名为input-file.result

在您的示例文件上运行它:

$ perl myscript.pl file.txt
found values in file.txt:
Bits: 32
Mux: 8
writing sum (0.14848) to the output file.txt.result

内容file.txt.result

//   copyright kkshlglkf
//   lhafslghldk
//   rsghlgsrlskl
//   sgkg
//   sgrjgrs
//   Memory:   BDRAM_SP
//   Bits:     32
//   Mux:      8
//   ladhdal:  sdj
//   zdfjhael: apfiehad
     slhgslfkghlkj
     slgdhlgfdkkdf
     Dataoutstage: None;
     TransparentMode: None;
     CellName: BDRAM_SP;
MemoryTemplate(BDRAM_SP)
{
 afljefkaf
 aslhkldfjfa
 fihhfejksgj
 dfhdhsgjshgf
 zdkjjgshgf
 sjfhfjkh
 sfdkjssjfh
Result: 0.14848;

如果要使用包含多个输入文件的脚本,可以按如下方式运行

perl myscript.pl file1 file2 file3 ...

这将创建输出文件file1.resultfile2.result等等

相关内容