Reputation: 679
I have a file that contains a lot of columns. One column contain a list of number:
asd "/$ 0
asd /"$ 1
add %$" 4
add "/% 18
ads "/% 24
add "/% 30
I would like to write a script using awk that allows to measure the difference between the number contained in a row and the row before the previous row (exemple: the difference between the third row and the first row) So the output will be :
4
17
20
12
How can I do that ? (if you have a good tutorial about awk, I will be grateful)
Upvotes: 0
Views: 1997
Reputation: 85795
Here is one method that uses the modulus operator to create an array that stores only the last elements needed for the calculation:
$ awk 'NR>2{print $3-a[(NR-2)%3]}{a[NR%3]=$3}' file
4
17
20
12
As for a good tutorial check out Effective AWK Programming.
Upvotes: 2
Reputation: 3756
Code for awk:
$ awk '{c=b;b=a;a=$3} c!="" {print $3-c}' file 4 17 20 12
And more general, based on sudo_O's answer here:
$ awk -v distance=1 'NR>distance{print $3-a[(NR-distance)%(distance+1)]}{a[NR%(distance+1)]=$3}' file 1 3 14 6 6 $ awk -v distance=2 'NR>distance{print $3-a[(NR-distance)%(distance+1)]}{a[NR%(distance+1)]=$3}' file 4 17 20 12 $ awk -v distance=3 'NR>distance{print $3-a[(NR-distance)%(distance+1)]}{a[NR%(distance+1)]=$3}' file 18 23 26
Upvotes: 3
Reputation: 224944
Here's a quick program I just whipped up (comments inline):
BEGIN {
# read the first line and save the number in 'a'
getline
a = $3
# read the second line and save the number in 'b'
getline
b = $3
}
# process the remaining lines
{
# print difference of this line's number and the number two rows back
print $3 - a
# shuffle the record keeping variables
a = b
b = $3
}
Example running it on your test input:
$ awk -f example inputfile
4
17
20
12
Upvotes: 1