代码之家  ›  专栏  ›  技术社区  ›  vehomzzz

计算两个文件中的数字差

  •  2
  • vehomzzz  · 技术社区  · 14 年前

    假设我有两个文件,每行有一个数字

    File 1      file 2
    0.12        0.11     
    0.121       0.454 
    ....        .... 
    

    我想在屏幕上创建每个数字之间的文件或输出差异,这样结果看起来像

     0.0099
    -0.333
     ......
    

    您可以使用bash/awk/sed

    5 回复  |  直到 14 年前
        1
  •  5
  •   ghostdog74    14 年前

    AWK

    awk '{getline t<"file1"; print $0-t}' file2  #file2-file1
    

    说明: getline t <"file1" 从中获取一行 file1 并将其值设置为变量 t . $0 是的当前记录 file2 那个锥子正在加工。剩下的只是减法,然后把结果打印出来。

    猛击

    exec 4<"file1"
    while read -r line
    do
        read -r s <&4
        echo "${line}-${s}" | bc
    done <"file2"
    exec >&4-
    
        2
  •  10
  •   Damodharan R    14 年前

    下面显示如何获取文件1-文件2

    $ cat file1
    0.12
    0.43
    -0.333
    
    $ cat file2
    -0.1
    -0.2
    0.2
    
    $ paste file1 file2 | awk '{print $1 - $2}'
    0.22
    0.63
    -0.533
    
        3
  •  0
  •   DVK    14 年前
    # cat f1
    0.12
    0.121
    # cat f2
    0.11     
    0.454
    
    # pr -m -t -s\  f1 f2 | gawk '{print $1-$2}'
    0.01
    -0.333
    
        4
  •  0
  •   Chen Levy    14 年前

    猛击:

    paste file1 file2 | while read a b ; do 
      echo "$a - $b" | bc
    done
    
        5
  •  0
  •   Dennis Williamson    14 年前
    paste -d - num1 num2 | bc
    

    编辑:

    此版本正确处理负数:

    yes '-' | head -n $(wc -l < num1) | paste -d ' ' num1 - num2 | bc