Shell – Subtracting same column between two rows in awk

awkshell-scripttext processing

I want to subtract the second line with the first line. The file is like this

tmptxt

A B 1 2 3 4 
C D 9 8 7 6

The desired output is

8 6 4 2

How to do this in awk?

I managed to output for a single column only:

awk '{$temp=$3-prev3; prev3=$3}{print $temp}'

Best Answer

A solution with awk

awk '
    NR==1 {split($0,a)}
    NR==2 {split($0,b)}
    END {for(i=1;i<=NF;i++) printf "%d ", b[i]-a[i]}
' input.txt

gives a result of

0 0 8 6 4 2

Since awk interpret strings without valid numbers as 0 during arithmetic operations, in case you want to remove the results in which the source field contains non-numeric values, you can do this by adding an additional condition.

awk '
    NR==1 {split($0,a)}
    NR==2 {split($0,b)}
    END {
        for(i=1;i<=NF;i++)
        if(a[i] ~ /^[0-9]+$/ && b[i] ~ /^[0-9]+$/)
        printf "%d ", b[i]-a[i]
    }
' input.txt

gives a result of

8 6 4 2
Related Question