我读了这个问题:Compare consecutive rows in awk/(or python) and random select one of duplicate lines . 现在我有一些额外的问题: 如果我不仅要对 x 值进行比较,还要对 y 值或更多列进行比较,我应该如何更改代码? 也许像
if ($1 != prev) && ($2 != prev) ???
换句话说:我想比较当前行的 x 值和 y 值是否与下一行的 x 值和 y 值相同。
数据:
#x y z
1 1 11
10 10 12
10 10 17
4 4 14
20 20 15
20 88 16
20 99 17
20 20 22
5 5 19
10 10 20
输出应该是这样的:
#x y z
1 1 11
10 10 17
4 4 14
20 20 15
20 88 16
20 99 17
20 20 22
5 5 19
10 10 20
或(由于随机选择)
#x y z
1 1 11
10 10 12
4 4 14
20 20 15
20 88 16
20 99 17
20 20 22
5 5 19
10 10 20
上面链接中的代码,它对 x 值进行处理,但不对 AND 条件中的 y 值进行处理:
$ cat tst.awk
function prtBuf( idx) {
if (cnt > 0) {
idx = int((rand() * cnt) + 1)
print buf[idx]
}
cnt = 0
}
BEGIN { srand() }
$1 != prev { prtBuf() }
{ buf[++cnt]=$0; prev=$1 }
END { prtBuf() }
最佳答案
应该这样做:
function prtBuf(idx) {
if (cnt > 0) {
idx = int((rand() * cnt) + 1)
print buf[idx]
}
cnt = 0
}
BEGIN { srand() }
$1 != prev1 || $2 != prev2 { prtBuf() }
{ buf[++cnt]=$0; prev1=$1; prev2=$2 }
END { prtBuf() }
关于bash - 比较awk中的连续行和多列并随机选择重复行之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38536450/