使用awk测量同一列中2个数字之间的差异

时间:2013-07-09 17:59:00

标签: linux shell awk

我有一个包含很多列的文件。一列包含数字列表:

   asd "/$ 0
   asd /"$ 1
   add %$" 4
   add "/% 18
   ads "/% 24
   add "/% 30

我想用awk编写一个脚本,允许测量行中包含的数字和前一行之前的行之间的差异(例如:第三行和第一行之间的差异) 所以输出将是:

4
17
20
12

我该怎么做? (如果你有关于awk的好教程,我将不胜感激)

3 个答案:

答案 0 :(得分:3)

的代码:

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

更一般,基于sudo_O的回答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

答案 1 :(得分:2)

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

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

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

答案 2 :(得分: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