0

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)

4

3 回答 3

3

的代码:

$ awk '{c=b;b=a;a=$3} c!="" {print $3-c}' 文件
4
17
20
12

更一般地说,基于 sudo_O 的回答

$ awk -v distance=1 'NR>distance{打印 $3-a[(NR-distance)%(distance+1)]}{a[NR%(distance+1)]=$3}' 文件
1
3
14
6
6

$ awk -v distance=2 'NR>distance{打印 $3-a[(NR-distance)%(distance+1)]}{a[NR%(distance+1)]=$3}' 文件
4
17
20
12

$ awk -v distance=3 'NR>distance{打印 $3-a[(NR-distance)%(distance+1)]}{a[NR%(distance+1)]=$3}' 文件
18
23
26
于 2013-07-09T18:22:58.463 回答
2

这是一种使用模运算符创建一个数组的方法,该数组仅存储计算所需的最后一个元素:

$ awk 'NR>2{print $3-a[(NR-2)%3]}{a[NR%3]=$3}' file
4
17
20
12

至于一个好的教程,请查看Effective AWK Programming

于 2013-07-09T18:12:13.277 回答
1

这是我刚刚编写的一个快速程序(内联评论):

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
}

在您的测试输入上运行它的示例:

$ awk -f example inputfile 
4
17
20
12
于 2013-07-09T18:07:25.913 回答