I have a textfile with:

1 100
2 80
3 70
4 64

Now I need another file that contains the first column equal to above and the second column should be the difference of to consecutive values of the above file, i.e.:

1 20
2 10
3 6

What is the most elegant/easy way to accomplish this with unix commands? What changes if I do not need a second file, but just have a third column in the original file with the desired differences.

Thanks a lot!


For calculations awk is more suitable

awk 'NR!=1{print a,b-$2};{a=$1;b=$2}'

If you'd like have a third column with difference just add it:

awk 'NR!=1{print a,b,b-$2};{a=$1;b=$2}'
| improve this answer | |

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.