首页 文章

减去列中的数字

提问于
浏览
1

在文件中我有一个包含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

4 回答

  • 1

    perly狗

    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
    
  • 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
    
  • 4
    #!/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
    
  • 0

    有了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
    

    或者让粘贴做gruntwork

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

相关问题