awk - 使用 awk 对重复字段进行分组

标签 awk

我有以下文件:

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/

相关文章:

html - 使用 BASH 和 AWK 创建 HTML 表格

linux - 提取两个模式之间第一次出现的文本

linux - 如何将多个 if 语句与多个结果结合起来?

linux - 需要帮助创建 pid 进程树

linux - 如何在彼此下一个一个地查找相似的值?

linux - AWK 错误 - grep 处或附近的语法错误

linux - 将空间上的一列拆分为两列

unix - 使用循环在两个模式之间进行 awk

linux - Bash:用零替换 "nothing"

bash - 使用冒号分隔的字符串遍历文件