Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate value differences between two neighboring fields

Tags:

I am trying to calculate distances between two neighboring fields. My input file is like below.

1 11160 11533 11556 11731 11822 11870 12149 12411 12461 12686 12829 13315 13420 ....

In the output, I want to keep the first field, and the following field would be the value differences between the current field and the next field, $2=$3-$2, $3=$4-$3 ...

A complete output will be like:

1 373 23 175 91 48 279 262 50 225 143 486 105...

How can I do this?

In my code, each value is printed as a new line also the numbers are reversely printed.

BEGIN {FS=" "}
{
        out[1]=$1
        for (i=2;i<=NF-1;i++) 
                out[i]=$(i+1)-$i
}
END{
        for (i in out)
               print out[i]
}

Here is current output

373 23 175 91 48 279 262 50 225 143 486 105 1

like image 968
shishi1181 Avatar asked Oct 03 '18 14:10

shishi1181


2 Answers

EDIT: Adding code suggested by anubhava sir too in comment section.

awk '{s=$1; for (i=2; i<NF; i++) s = s OFS $(i+1) - $i; print s}' Input_file

Could you please try following.

awk '{printf $1 OFS;for(i=2;i<NF;i++){printf("%d%s",$(i+1)-$i,i==(NF-1)?ORS:OFS)}}' Input_file

Output will be as follows.

1 373 23 175 91 48 279 262 50 225 143 486 105

Explanation: Adding explanation too here.

awk '
{
  printf $1 OFS                                 ##Printing first field and OFS(whose value is space by default).
  for(i=2;i<NF;i++){                            ##Starting for loop from value of 2 to till NF-1 value where NF is number of field in current line.
    printf("%d%s",$(i+1)-$i,i==(NF-1)?ORS:OFS)  ##Printing diffrence of next field and current field and checking condition for 2nd print if i==NF-1 then new line else print space for that line.
  }                                             ##Closing for loop block here.
}
' Input_file                                    ##Mentioning Input_file name here.
like image 67
RavinderSingh13 Avatar answered Nov 15 '22 00:11

RavinderSingh13


awk '{printf("%d",$1); for (i=2;i<NF;i++) printf(" %d",$(i+1)-$i)}' file

Output:

1 373 23 175 91 48 279 262 50 225 143 486 105
like image 42
Cyrus Avatar answered Nov 14 '22 23:11

Cyrus