【问题标题】:Calculate difference of numbers in two files计算两个文件中数字的差异
【发布时间】:2011-01-25 00:16:33
【问题描述】:

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

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

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

 0.0099
-0.333
 ......

你可以使用 bash/awk/sed

【问题讨论】:

    标签: bash sed awk scripting


    【解决方案1】:

    下面展示了如何获取file1-file2

    $ 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
    

    【讨论】:

    • 如果其中一个文件有空行怎么办
    • 如果有空行,则减法为零。 $ cat file1 0.12 0.43 -0.333 10 $ cat file2 -0.1 -0.2 0.2 $ paste file1 file2 | awk '{打印 $1 - $2}' 0.22 0.63 -0.533 10
    【解决方案2】:

    awk

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

    解释:getline t &lt;"file1"file1 获取一行并将其值放入变量t$0 是 awk 正在处理的 file2 的当前记录。剩下的只是减法并将结果打印出来。

    重击

    exec 4<"file1"
    while read -r line
    do
        read -r s <&4
        echo "${line}-${s}" | bc
    done <"file2"
    exec >&4-
    

    【讨论】:

      【解决方案3】:
      # 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】:

        重击:

        paste file1 file2 | while read a b ; do 
          echo "$a - $b" | bc
        done
        

        【讨论】:

        • 这个解决方案对于大文件来说太fork-heavy(它不需要。)
        【解决方案5】:
        paste -d - num1 num2 | bc
        

        编辑:

        这个版本可以正确处理负数:

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

        【讨论】:

        • 你的第二个版本有很多开销。
        • @ghostdog74:可能有点开销,但它怎么会有很多呢?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多