gpt4 book ai didi

perl - awk:打印一组行中的三行

转载 作者:行者123 更新时间:2023-12-02 07:37:41 25 4
gpt4 key购买 nike

我有一个包含多行的文本文件,从中我只需要每组的前三行。

文件:

test1|pass
test1|pass
test1|pass
test1|pass
test1|pass
test2|fail
test2|fail
test2|fail
test2|fail
test3|pass
test3|pass
test3|pass
test3|pass

预期输出:

test1|pass
test1|pass
test1|pass
test2|fail
test2|fail
test2|fail
test3|pass
test3|pass
test3|pass

到目前为止我尝试了什么:

BEGIN {
FS = "|"
}
$1==x {
if (NR % 5 <= 3) {
print $0
}
next
}
{
x=$1
print $0
}

END {
printf "\n"
}

最佳答案

你可以像这样相当简洁地做到这一点:

awk -F'|' '++a[$1] <= 3' infile

输出:

test1|pass
test1|pass
test1|pass
test2|fail
test2|fail
test2|fail
test3|pass
test3|pass
test3|pass

解释

a 是一个关联数组。我们使用每一行的第一个元素 ($1) 作为 a 的键并增加它的值。然后将该值与 3 进行比较,如果比较为真,则执行默认 block ({print $0})。

关于perl - awk:打印一组行中的三行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14749838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com