使用unix查找文件中存在的两个连续数字之间的N max差异

时间:2016-01-14 14:24:34

标签: shell unix

整数存储在文件中,我需要找到文件中存在的两个连续数字之间的Max和N Max差异(每行/每行一个整数) 例如

 12
 15
 50
 80

最大差异:35(50 -15)并且说N = 2所以第1最大35和第2最大:30

1 个答案:

答案 0 :(得分:1)

#!/usr/bin/awk -f
NR>1{ diff = $0 - prev
      for (i = 0; i < N; ++i)
        if (diff > maxdiff[i])
        { # sort new max. diff.
          for (j = N; --j > i; ) if (j-1 in maxdiff) maxdiff[j] = maxdiff[j-1]
          maxdiff[j] = diff
          break
        }
    }
    { prev = $0 }
END { for (i in maxdiff) print maxdiff[i] }

- e。例如,如果脚本名为nmaxdiff.awk且数字存储在文件numbers中,请输入

nmaxdiff.awk N=2 numbers