【问题标题】:Subtracting numbers in a column减去一列中的数字
【发布时间】:2016-02-06 00:46:06
【问题描述】:

在一个文件中,我有一列包含 10 个元素的数字。我想从第 3 个数字中减去第 1 个数字,从第 4 个数字中减去第 2 个数字,从第 5 个数字中减去第 3 个数字,从第 6 个数字中减去第 4 个数字,依此类推,从第 10 个数字中减去第 8 个数字。

例如:

10.3456
6.3452
11.2456
5.6666
10.5678
6.4568
14.7777
7.5434
16.5467
8.9999

并得到一个带有减法的文件

3rd-1st
4th-2nd
5th-3rd
6th-4th
7th-5th
8th-6th
9th-7th
10th-8th

【问题讨论】:

    标签: bash


    【解决方案1】:

    又快又脏:

    $  awk '{a[NR]=0+$0}END{for(i=3;i<=NR;i++)print a[i]-a[i-2]}' file
    0.9
    -0.6786
    -0.6778
    0.7902
    4.2099
    1.0866
    1.769
    1.4565
    

    更新:想出了另一个有趣的方法:

    $ awk 'NF>1{print $1-$2}' <(paste  <(sed -n '3,$p' file) file)  
    0.9
    -0.6786
    -0.6778
    0.7902
    4.2099
    1.0866
    1.769
    1.4565
    

    update2,把结果做成CSV:

    kent$  awk '{a[NR]=0+$0}END{for(i=3;i<=NR;i++)
                printf "%s%s", a[i]-a[i-2],NR==i?RS:","}' file
    0.9,-0.6786,-0.6778,0.7902,4.2099,1.0866,1.769,1.4565
    

    【讨论】:

    • 谢谢@Kent ...如果我想保存这些数据,在一行中而不是在列中,并用逗号 (,) 分隔,你该怎么做?
    • 更新3? paste -d- &lt;(tail -n +3 file) &lt;(head -n -2 file) | bc | paste -sd,
    • @kent 我稍后检查 update2,现在我的孩子需要我的时间 :) 谢谢,我稍后检查
    • @kent 我检查了updated2,它运行良好!,你能解释一下命令吗?如果可以的话,我将不胜感激。
    • @EnricAgudPique 它将所有行保存在一个数组中,并进行数学计算。对于输出,printf 会让你控制你想要什么样的输出格式。
    【解决方案2】:
    #!/bin/bash
    #Create an array
    mapfile -t lines < inputFile
    
    
    output=()
    for index in "${!lines[@]}"; do
    # Check if the index + 2 exist
        if [[ ${lines[$(expr $index + 2)]} ]]; then
        #It does exist, do the math
            output+=("$(expr ${lines[$index]} + ${lines[$(expr $index + 2)]})")
        fi
    
    done
    
    printf "%s\n" "${output[@]}" > output
    

    【讨论】:

      【解决方案3】:

      佩利狗

      perl -ne '$a{$.}=$_;print $_-$a{$.-2}."\n" if $a{$.-2}' file
      

      创建一个数组 如果之前存在两行的键,则打印该行减去数组中的值。

      0.9
      -0.6786
      -0.6778
      0.7902
      4.2099
      1.0866
      1.769
      1.4565
      

      在肯特回答中要求的连续

      perl -ne '$a{$.}=$_;print $_-$a{$.-2}.(eof()?"\n":",") if $a{$.-2}' file
      
      0.9,-0.6786,-0.6778,0.7902,4.2099,1.0866,1.769,1.4565
      

      【讨论】:

        【解决方案4】:

        有了 awk,我会写

        awk -v ORS="" '
            {a=b; b=c; c=$0}                  # remember the last 3 lines
            NR >= 3 {print sep c-a; sep=","}  # print the difference
            END {print "\n"}                  # optional, add a trailing newline.
        ' file
        

        或者让粘贴完成繁琐的工作

        awk '{a=b;b=c;c=$0} NR >= 3 {print c-a}' file | paste -sd,
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-11
          • 1970-01-01
          相关资源
          最近更新 更多