0

我之前问过如何使用 awk 更正计数数据中的错误,其中我的数据的第一列是用于标识正在测量的子竞技场的数字,第二列是来自该子竞技场的计数数据。计数是自动的,程序会出错(下面用# 表示),它偶尔会“计数错误”,因为正在计数的动物已经移出特定子竞技场的范围。

1       0
1       2
1       6
1       7
1       7
1       8
1       7 #
1       7 #
1       9
2       0
2       0
2       1
2       4
2       3 #
2       3 #
2       4
2       4
2       6

我想像这样更正上述内容:

1       0
1       2
1       6
1       7
1       7
1       8
1       8
1       8
1       9
2       0
2       0
2       1
2       4
2       4
2       4
2       4
2       4
2       6

好心建议的代码不包含用于在每个竞技场的数据中更正的 for 循环(每个文件总共有 20 个),我一直在尝试解决这个问题,但是遇到了非常困难的问题,语法错误有时,有时非法语句错误。我会很感激任何关于为什么以下内容不起作用的提示(对不起,我是个新手,这是我尝试过的众多迭代之一,但没有一个是漂亮的):

awk 'i=1; i<=20; i++; $1=i {NR > 1 && $2 < p {$2 = p} {p = $2} 1}' infile > outfile
4

1 回答 1

2

与其计算行数,不如让另一个变量跟踪行号,p如果行号增加,它会重置:

awk '$1 > l { l = $1; p = 0 } $2 < p { $2 = p } { p = $2 } 1' input-file

First the first position ($1) is compared to the value in the l variable (that defaults to 0). If it's greater, l is set to $1, and p is reset to 0. Then the second position ($2) is compared to p, and if it's less set to p. Finally, p is set to the value of the (possibly changed) $2. The final 1 just means "print"; otherwise the command would do all the processing but not print any of it.

于 2012-07-31T03:30:42.773 回答