Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

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
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.

share|improve this answer
    
Excellent solution, exactly what I was looking for! –  Tobi Lehman Feb 2 at 17:45
add comment

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]

share|improve this answer
add comment

Your Answer

 
discard

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.