Prayag
Prayag

Reputation: 211

Using awk, subtract with previous row in all columns and print the result

I need your guidance in one liner command for linux using awk, subtract the row with previous row recursively in all columns and then print the difference values.

I have input as

2021-02-15_16 101242 102108 17572 84538
2021-02-15_17 101235 102077 17625 84445

Expected output

 2021-02-15_17  -7  -31 53  -93

I tried this by myself but with no luck.

    cat test |awk 'NR==1{s=$3;next}{s-=$3}END{print s}' --> this displays only for 1 column

cat test | awk  'NR==1 {for(i=3; i<=NF; i++){s=$i;next}{s-=$i}{print s}}'

Upvotes: 1

Views: 1254

Answers (1)

anubhava
anubhava

Reputation: 784998

You may use this awk:

awk 'NR > 1 {for (i=2; i<=5; ++i) $i -= a[i]; print} {split($0,a)}' file

2021-02-15_17 -7 -31 53 -93

To make it more readable:

awk 'NR > 1 {
   for (i=2; i<=5; ++i)
      $i -= a[i]
   print
}
{
   split($0,a)
}' file

Upvotes: 3

Related Questions