我正在尝试使用awk来识别文件中的重复记录,并将更改直接应用于该文件。该文件有六列,没有标题。我的目标是编辑重复记录的第二列,使其在每次出现时都添加1,从而使其唯一。数据如下:
1 A B C D E
1 A B C D E (This is a duplicate record1)
1 A B C D E (This is a duplicate record2)
2 F G H I J
3 K L M N O
所需输出
1 A B C D E
1 A-1 B C D E
1 A-2 B C D E
2 F G H I J
3 K L M N O
编辑:
我试过这篇文章中的代码awk 'cnt[$0]++{$0=$0" variant "cnt[$0]-1} 1' file
如何用awk重命名重复的行?但是数字被添加在记录的末尾
使用您显示的示例,请尝试以下awk
代码。
上述溶液的一种线性形式是:
awk '++arr1[$0]>1{$2=$2"-"(++arr[$0])}1' Input_file
OR
awk '
++arr1[$0]>1{
$2=$2"-"(++arr[$0])
}
1
' Input_file
说明:添加对上述awk
代码的详细说明。
awk ' ##Starting awk program from here.
++arr1[$0]>1{ ##Checking condition if current line occurrence in arr1 is greater than 1
$2=$2"-"(++arr[$0]) ##Then add values to $2 as per condition. If $0 occurrence in arr is more than 1 then add - followed by its occurrence.
}
1 ##1 will print edited/non-edited line.
' Input_file ##Mentioning Input_file name here.
在脚本中,只需将$0=$0
更改为$2=$2
,即可将新文本附加到第二个字段的末尾,而不是行的末尾,例如:
$ awk 'cnt[$0]++{$2=$2 "-" (cnt[$0]-1)} 1' file | column -t
1 A B C D E
1 A-1 B C D E
1 A-2 B C D E
2 F G H I J
3 K L M N O
nawk 'BEGIN { _+=_^=___=" " } $_ = $_ ((__=____[$!_]++) ?"-"__:___)'
gawk 'BEGIN { _+=_^=___=" " } $_ =__[$!_]++ ? $_ "-"(__[$!_]-!!_):$_ ___'
明版本:mawk/mawk2 '$(_+=_^=_<_) = $_ ((__=___[$-(_=" ")]++) ? "-" __: (_)_)'
awk '$2=$2 ((_=__[$0]++)?"-"_:" ")'