1

I want to do the following calculation using awk: (Element2-Element1)/Element1

Element 1 Position: Column x, Row j

Element 2 Position: Column x, Row i

let x=1, j=2, i=6

Input:

0 2 7 2 3 3 

desired Output:

0.5 

I dont know how to change FNR inside of the AWK script and opening an awk process just to read each Element and then dividing them by using another awk doesnt feel good.

Thanks in advance!

4
  • elaborate your conditions: could j be greater than i ? Commented Sep 19, 2017 at 17:39
  • Hi Roman, j will not be greater than i. It will always be the first line of a column. Im trying to figure out how to skip possible zeros in the first line of each column right now. Commented Sep 19, 2017 at 17:41
  • what do mean skip? If the third line starts with 0 - should it be skipped, should the remaining lines be reordered? Commented Sep 19, 2017 at 17:45
  • What formula did you use to get to the resulting output of 0.5. Can you run through your mathematics with us, manually, so that we can translate into awk? Commented Sep 19, 2017 at 17:55

2 Answers 2

1

You can use this awk command:

awk -v x=1 -v j=2 -v i=6 'NR==j{e1=$x} NR==i{e2=$x} END{if (el) print (e2-e1)/e1}' file 0.5 
Sign up to request clarification or add additional context in comments.

2 Comments

how can i catch the 0 in the beginning of each line? I dont want inf as output. Or is it possible to take the 2nd value in each column, if the 1st is equal to 0?
In that case use { if (e1) print (e2-e1)/e1 } in END block.
1

j will not be greater than i.

awk solution:

awk 'BEGIN{ x=1; j=2; i=6 }NR==j{ el1=$x }NR==i{ print ($x-el1)/el1; exit }' file 0.5 

2 Comments

@anubhava, that condition was not mentioned in the question, that's your condition
@anubhava, j will not be greater than i.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.