您好,我有一个 csv 文件,其中数据超过 10 万,并由管道分隔,看起来像
2|dfdf|er34Sr|afe|&*&|djhgjdsf|jhfgdhj12|dse|dsR|fcdf|erer|ddff|vcdf||||||
3||||dfrg||DFgfg||FDGRFG|FGB|FG|4546|@#$|FGFDG|DGFDFG|||FGfg||DGF |||GF |||
dhgfyukdsf|dfdf|#%||fghfhj|nvcbd,|bhd|cmnbch|vjh|jhfur||mhvjh|mnbvm||||
hjgg|||||gy|fdf|D|||fgfg|gfgf|Fgfg|FGfg|Sf||dfdfbhj|segrhb|zaefef|||
2|dfdf|er34Sr|afe|&*&|djhgjdsf|jhfgdhj12|dse|dsR|fcdf|erer|ddff|vcdf||||||
2|dfdf|er34Sr|afe|&*&|djhgjdsf|jhfgdhj12|dse|dsR|fcdf|erer|ddff|vcdf||||||
2|dfdf|er34Sr|afe|&*&|djhgjdsf|jhfgdhj12|dse|dsR|fcdf|erer|ddff|vcdf||||||
3||||dfrg||DFgfg||FDGRFG|FGB|FG|4546|@#$|FGFDG|DGFDFG|||FGfg||DGF |||GF |||
3||||dfrg||DFgfg||FDGRFG|FGB|FG|4546|@#$|FGFDG|DGFDFG|||FGfg||DGF |||GF |||
3||||dfrg||DFgfg||FDGRFG|FGB|FG|4546|@#$|FGFDG|DGFDFG|||FGfg||DGF |||GF |||
我想在每次执行脚本时检查特定列中数据的重复情况
例如,我想检查所有 CSV 文件中的第 1,7,12,14 列是否包含相同的数据,如果是,则仅显示那些重复的数据
我努力了
awk -F"|" '{
if (x[$'"$ColumnNo1"'$'"$ColumnNo2"'$'"$ColumnNo3"'$'"ColumnNo4"'])
{x_Count[$'"$ColumnNo1"'$'"$ColumnNo2"'$'"$ColumnNo3"'$'"ColumnNo4"']++;
print $0;
if(x_Count[$'"$ColumnNo1"'$'"$ColumnNo2"'$'"$ColumnNo3"'$'"ColumnNo4"']==1)
{
print x[$'"$ColumnNo1"'$'"$ColumnNo2"'$'"$ColumnNo3"'$'"ColumnNo4"']}}
x[$'"$ColumnNo1"'$'"$ColumnNo2"'$'"$ColumnNo3"'$'"ColumnNo4"']=$0}' csvfilename.csv
但我没有得到任何输出
$ColumnNo1,$ColumnNo2,$ColumnNo3
是 shell 脚本变量
请帮忙 :)
答案1
除了很少有专门的工具可以使用数据集(例如csv工具)
awk -F"|" '
{
r = $w SUBSEP $x SUBSEP $y SUBSEP $z #prepare index from 4 fields data
}
R[r]{ #if index present in array already
if ( R[r] != 1){ #if it is a first repetition
print R[r] #print line stored in array
R[r] = 1 #mark element «not a first time»
}
print #print present line
next #pass rest of code(goto next line)
}
{
R[r] = $0 #store line in array (first time only)
}
' w=$ColumnNo1 x=$ColumnNo2 y=$ColumnNo3 z=$ColumnNo4 file.csv
答案2
试试这个(注意你的 shell 变量必须是整数):
awk -v C1="$ColumnNo1" -v C2="$ColumnNo2" -v C3="$ColumnNo3" -v C4="$ColumnNo4" -F'|' '
{ a1[$C1]++; a2[$C2]++; a3[$C3]++; a4[$C4]++}
END {
printf "Non-unique entries in column %d\n", C1
for (key in a1) {
if (a1[key] > 1) print key
}
printf "Non-unique entries in column %d\n", C2
for (key in a2) {
if (a2[key] > 1) print key
}
printf "Non-unique entries in column %d\n", C3
for (key in a3) {
if (a3[key] > 1) print key
}
printf "Non-unique entries in column %d\n", C4
for (key in a4) {
if (a4[key] > 1) print key
}}' <myfile.csv