我有以下文件:
ID|2018-04-29
ID|2018-04-29
ID|2018-04-29
ID1|2018-06-26
ID1|2018-06-26
ID1|2018-08-07
ID1|2018-08-22
并使用 awk,我想添加 $3
根据 $1
和 $2
对重复的 ID 进行分组,以便输出为
ID|2018-04-29|group1
ID|2018-04-29|group1
ID|2018-04-29|group1
ID1|2018-06-26|group2
ID1|2018-06-26|group2
ID1|2018-08-07|group3
ID1|2018-08-22|group4
我尝试了以下代码,但它没有给我想要的输出。另外,我不确定是否可以将其应用于包含日期的列。
awk -F"|" '{print $0,"group"++seen[$1,$3]}' OFS="|"
任何关于如何使用 awk(如果可能的话,单线)实现它的提示将不胜感激。
最佳答案
使用您显示的示例,请尝试以下 awk
代码。
awk -v OFS="|" '!arr[$0]++{count++} {print $0,"group"count}' Input_file
说明:为上述添加详细说明。
awk ' ##Starting awk program from here.
BEGIN{ ##Starting BEGIN section of this program from here.
OFS="|" ##Setting OFS to | here.
}
!arr[$0]++{ ##Checking if current line is NOT present in array then do following.
count++ ##Increasing count with 1 here.
}
{
print $0,"group"count ##Printing current line with group and count value here.
}
' Input_file ##Mentioning Input_file name here.
关于awk - 使用 awk 对重复字段进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68288703/