4

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:

201309,694
201310,699
201311,700
201312,705
201401,713
201402,740

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

201310-201309,699-694
201311-201310,700-699
201312-201311,705-700
201401-201312,713-715
201402-201401,740-713

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

2 Answers 2

5

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
201310-201309,699-694
201311-201310,700-699
201312-201311,705-700
201401-201312,713-705
201402-201401,740-713

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.

2
  • Excellent solution, exactly what I was looking for! Commented Feb 2, 2014 at 17:45
  • I use this so much I made a little script here. Commented Jun 13, 2014 at 21:32
4

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

#!/usr/bin/awk -f

BEGIN {
    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]

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.