physkets
physkets

Reputation: 182

Difference between adjacent data rows, with multiple columns

If I have:

1  2  3  4  5  6  .  .
3  4  5  4  2  1  .  .
5  7  5  7  2  0  .  .
.
.

I want to show the difference of adjacent data rows, so that it would show:

2  2  2  0 -3 -5  .  .
2  3  0  3  0 -1  .  .
.
.

I found the post difference between number in the same column using AWK, and adapting the second answer, I thought that this will do the job:

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

But that produces output in and of a single column. How do I get it to retain the column structure of the data?

Upvotes: 2

Views: 188

Answers (3)

Ed Morton
Ed Morton

Reputation: 203635

$ cat tst.awk
NR>1 {
    for (i=1; i<=NF; i++) {
        printf "%2d%s", $i - p[i], (i<NF ? OFS : ORS)
    }
}
{ split($0,p) }

$ awk -f tst.awk file
 2  2  2  0 -3 -5
 2  3  0  3  0 -1

Upvotes: 1

James Brown
James Brown

Reputation: 37404

Written out:

$ cat > subtr.awk
{
    for (i=1; i<=NF; i++) b[i]=a[i]
    # for (i in a) b[i]=a[i]
    n=split($0,a)
}
NR > 1 {
    for (i=1; i<=NF; i++) {
    #for(i in a) {
        printf "%s%s", a[i]-b[i], (i==n?ORS:OFS)
    }
delete b
}

Test it:

$ awk -f subtr.awk file
2 2 2 0 -3 -5
2 3 0 3 0 -1

Upvotes: 0

Michael Vehrs
Michael Vehrs

Reputation: 3363

Try something like this:

awk '{for (i=1; i <= NF; i++) { c[i] = $i - c[i] }; count = NF }
     END { for (i = 1; i <= count; i++) { printf c[i] " "}}' numbers

Upvotes: 0

Related Questions