bash - Use the previous row for mathematical operation in current line -


i have following sample data:

co1 co2 co3 100 200 300 110 230 310 125 235 320 

i need perform below logic on data:

(col2 - col2 of previous line)/(col1 - col1 of previous line) (col3-col3 of previous line)/(col1 - col1 of previous line)  

which translate to:

(230-200)/(110-100) (310-300)/(110-100) (235-230)/(125-110) (320-310)/(125-110) 

i tried:

cat sample |awk 'nr>1' |'nr>1{f=$1;s=$2;t=$3;next} {print f,s;print $2-s/$1-f,$3-t/$1-f}' 

desired output:

3   1 0.3 0.6 

with logic output 1 less row, first row consumed second row.

error below data:

 104937 20776001011 6893034089  104937 20776001011 6893034089  104938 20776062501 6893040119  104938 20776062501 6893040119  104938 20776062501 6893040119  104938 20776062501 6893040119  104938 20776062501 6893040119  104939 20776124802 6893047227  104939 20776124802 6893047227  104939 20776124802 6893047227  104939 20776124802 6893047227  104940 20776178348 6893051452  104940 20776178348 6893051452  104940 20776178348 6893051452  104940 20776178348 6893051452  104940 20776178348 6893051452  104941 20776235367 6893055075  104941 20776235367 6893055075  104941 20776235367 6893055075  104941 20776235367 6893055075   61490 6030 awk: cmd. line:1: (filename=- fnr=4) fatal: division 0 attempted 

another using awk. each record split array a used on next iteration:

$ awk 'nr>2{print ($2-a[2])/($1-a[1]),($3-a[3])/($1-a[1])} nr>1{split($0,a)}' file 3 1 0.333333 0.666667 

instead of printing raw values can use printf format output: printf "%.01f %.01f\n", ... stolen referred (and rewarded :) @ravindersingh13's answer... output:

3.0 1.0 0.3 0.7 

%g %g output:

3 1 0.333333 0.666667 

just choose output type differs least preferred.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -