
저는 다음과 같은 CSV 데이터 세트로 작업하고 있습니다.
year,manufacturer,brand,series,variation,card_number,card_title,sport,team
2015,Leaf,Trinity,Printing Plates,Magenta,TS-JH2,John Amoth,Soccer,
2015,Leaf,Trinity,Printing Plates,Magenta,TS-JH2,John Amoth,Soccer,
2015,Leaf,Trinity,Printing Plates,Magenta,TS-JH2,John Amoth,,
2015,Leaf,Metal Draft,Touchdown Kings,Die-Cut Autographs Blue Prismatic,TDK-DF1,Darren Smith,Football,
2015,Leaf,Metal Draft,Touchdown Kings,Die-Cut Autographs Blue Prismatic,TDK- DF1,Darren Smith,Football,
2015,Leaf,Trinity,Patch Autograph,Bronze,PA-DJ2,Duke Johnson,Football,
2015,Leaf,Army All-American Bowl,5-Star Future Autographs,,FSF-RG1,Rasheem Green,Soccer,
여기에는 제거해야 할 중복 항목이 많이 포함되어 있습니다(기록의 한 인스턴스 유지). 기반으로CSV 파일에서 중복 항목 제거나는 이것을 사용해 왔으며 sort -u file.csv --o deduped-file.csv
이와 같은 예에 아주 효과적입니다.
2015,Leaf,Trinity,Printing Plates,Magenta,TS-JH2,John Amoth,Soccer,
2015,Leaf,Trinity,Printing Plates,Magenta,TS-JH2,John Amoth,Soccer,
하지만 유사한 예는 포착되지 않았습니다.
2015,Leaf,Trinity,Printing Plates,Magenta,TS-JH2,John Amoth,Soccer,
2015,Leaf,Trinity,Printing Plates,Magenta,TS-JH2,John Amoth,,
데이터는 불완전하지만 동일한 내용을 나타냅니다.
지정된 필드(예: 연도, 제조업체, 브랜드, 시리즈, 변형)를 기반으로 중복 항목을 제거할 수 있습니까?
답변1
처음 5개 필드의 "키"를 만든 다음 키가 처음 표시될 때만 한 줄을 인쇄합니다.
awk -F, '
{key = $1 FS $2 FS $3 FS $4 FS $5}
!seen[key]++
' file
year,manufacturer,brand,series,variation,card_number,card_title,sport,team
2015,Leaf,Trinity,Printing Plates,Magenta,TS-JH2,John Amoth,Soccer,
2015,Leaf,Metal Draft,Touchdown Kings,Die-Cut Autographs Blue Prismatic,TDK-DF1,Darren Smith,Football,
2015,Leaf,Trinity,Patch Autograph,Bronze,PA-DJ2,Duke Johnson,Football,
2015,Leaf,Army All-American Bowl,5-Star Future Autographs,,FSF-RG1,Rasheem Green,Soccer,
답변2
먼저 awk로 장식하여 정렬 중에 헤더 행을 맨 위에 유지한 다음 awk+sort+cut을 사용합니다.
$ awk -v OFS=',' '{print (NR>1), $0}' file | sort -u -t, -k1,6 | cut -d, -f2-
year,manufacturer,brand,series,variation,card_number,card_title,sport,team
2015,Leaf,Army All-American Bowl,5-Star Future Autographs,,FSF-RG1,Rasheem Green,Soccer,
2015,Leaf,Metal Draft,Touchdown Kings,Die-Cut Autographs Blue Prismatic,TDK-DF1,Darren Smith,Football,
2015,Leaf,Trinity,Patch Autograph,Bronze,PA-DJ2,Duke Johnson,Football,
2015,Leaf,Trinity,Printing Plates,Magenta,TS-JH2,John Amoth,Soccer,
답변3
비 awk
해결책: 간단히 를 사용하여 sort
필드 1~5를 비교 필드로 정의하고 -k
이를 ,
필드 구분 기호( -t
)로 사용하고 -u
고유한 항목만 선택할 수 있습니다.
sort -t, -k1,5 -u infile
그러나 이렇게 하면 헤더 행이 끝에 배치됩니다. 예를 들어 역순 정렬을 사용 -r
하거나 헤더 행을 분리 하세요.
{ sed 1q infile ; sed 1d infile | sort -k1,5 -t, -u ; }