0

I have a file

A 1
A 2
A 4
A 6

I want to print the difference between adjacent values (below-above) in column 2 to a new column 3, to get this

A 1
A 2 1
A 4 2
A 6 2

I have discovered something like this on SO, but failed to print it as a new column.

awk 'NR>1{print $1-p} {p=$1}' file
5

To modify the given code in question

$ awk 'NR>1{$3=$2-p} {p=$2} 1' file 
A 1
A 2 1
A 4 2
A 6 2
  • Fields are indexed from 1, so use $2 for second column
    • $0 contains entire input record
  • After modifying, you need to print the record. Default action is printing contents of $0 if condition is true. 1 is used idiomatically for such cases
  • Now I would like to modify the script so it prints the quotient of the division by the value 10 steps above. I tried awk 'NR>1{$3=$2/p} {p=$2} 10' file but failed. Maybe I misunderstood some parts of the script. How should I correct it? – Johnny Tam Oct 4 '17 at 4:14
  • @JohnnyTam I didn't get what are you trying... can you tell the three values you need? is this what you need? awk 'NR>1{$3=int($2/p)} {p=$2} 1' – Sundeep Oct 4 '17 at 4:58
  • Please go here: unix.stackexchange.com/questions/396195/… for a simplified illustration. :) – Johnny Tam Oct 5 '17 at 6:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.