Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I run into this problem a lot with data, if I have some integers, I frequently want to look at differences between adjacent integers, I usually solve this in Ruby or Python, but I think such a thing could be done in awk, and I'd prefer that.

I have a table of data such as:


And I would like to find the adjacent differences, that is:


I found the function getline in the awk manpage, but I haven't been able to use it successfully.

share|improve this question
up vote 5 down vote accepted

This one-liner produces the output with the minus signs:

awk -F, '{if (NR>1) {print $1 "-" a "," $2 "-" b} a=$1 ; b=$2}' numbers

This version shows the actual differences:

awk -F, '{if (NR>1) {print $1-a, $2-b } a=$1 ; b=$2}' numbers
1 5
1 1
1 5
89 8
1 27

In both cases, the awk program begins with an option to set the field separator to a comma (-F,). Then, for each line in the file, an if statement is executed: if we are past the first line ((NR>1) then the differences are printed. The next two commands (a=$1 ; b=$2) update the variables that store the last values.

share|improve this answer
Excellent solution, exactly what I was looking for! – tlehman Feb 2 '14 at 17:45
I use this so much I made a little script here. – tlehman Jun 13 '14 at 21:32

No need for getline. Just keep track of the columns in the AWK script, e.g.

#!/usr/bin/awk -f

    FS="," # We separate on the comma character

    if(NR > 0) { ## NR is the current line number
            print $1 "-" old[1] "," $2 "-" old[2]
    for(field = 1; field <= 2; field++) {
            old[field] = $(field)

I assume you want to post "thisline_field1-lastline_field1,thisline_field2-lastline_field2" as a literal string; if you want to subtract, it would be print $1 - old[1] "-" $2 - old[2]

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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