【问题标题】:Subtract all entries in one file from corresponding entries in another file without considering the missing value从另一个文件中的相应条目中减去一个文件中的所有条目,而不考虑缺失值
【发布时间】:2016-10-27 16:19:51
【问题描述】:

我有两个行数和列数相等的文件。我想从另一个文件中的对应条目中减去一个文件中的所有条目,而不考虑缺失值。例如

ifile1.txt    
3  5  2  2
1  ?  2  1
4  6  5  2
5  5  7  1

ifile2.txt
1  2  1  3
1  3  0  2
2  ?  5  1
0  0  1  1

这里“?”是缺失值,在计算中不应该考虑。

ofile.txt i.e. [(ifile1.txt) - (ifile2.txt)]
2.00  3.00  1.00 -1.00 
0.00  ?     2.00 -1.00 
2.00  ?     0.00  1.00 
5.00  5.00  6.00  0.00 

我可以通过以下方式做到没有任何缺失值。但是不能像这里“?”这样的缺失值成功。

paste ifile1.txt ifile2.txt > ifile3.txt
awk '{n=NF/2; for (i=1;i<=n;i++) printf "%5.2f ", $i-$(i+n); print ""}' ifile3.txt > ofile.txt

【问题讨论】:

    标签: linux shell awk subtraction


    【解决方案1】:

    没有测试,但是这样的东西应该可以工作

    $ paste ifile1.txt ifile2.txt |
      awk -v q='?' '{n=NF/2; 
                     for(i=1;i<=n;i++) 
                       printf "%5s ", (($i==q||$(i+n)==q)?q:$i-$(i+n)); 
                     print ""}' > ofile.txt
    

    【讨论】:

    • 非常感谢您的支持。这是给出零“0”值而不是缺少“?”因为格式。所以我用 printf "%5s " 而不是 printf "%5.2f "。工作正常。
    【解决方案2】:

    我开始研究如何同时读取 2 个文件,即。如何松开paste。在 awk 中:

    $ cat mm.awk
    NR>FNR { exit }                       # after file1 exit
    {
        split($0,a," ")                   # split record from file1 to array a
        getline < ARGV[2]                 # read record from the file2
        for(i=1;i<=NF;i++)                # one for for both 
            printf "%s%s", ( a[i]!="?" && $i!="?" ? a[i]-$i : "?" ), ( i==NF ? ORS : OFS )
    }                                     # on prev rec, if "?" in either, output "?"
    

    运行它:

    $ awk mm.awk file1 file2
    2 3 1 -1
    0 ? 2 -1
    2 ? 0 1
    5 5 6 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-26
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      相关资源
      最近更新 更多