ลบรหัส test case ที่ซ้ำกันจาก manifest การรัน test หรือคำยืนยันซ้ำในชุดทดสอบที่สร้างขึ้น ลบข้อความ error ซ้ำจาก log เพื่อดูชุดของความล้มเหลวที่ไม่ซ้ำกัน
วิศวกรรมข้อมูล
ตัดแถวซ้ำออกจากไฟล์ CSV ที่ export มาหรือผลลัพธ์ SQL query ที่วางเป็นข้อความ ทำความสะอาดรายการอีเมล, รายการ ID ผู้ใช้ หรือรายการ tag ก่อนนำเข้าสู่ฐานข้อมูลหรือ pipeline
ลบบรรทัดซ้ำด้วยโค้ดใน JavaScript, Python, Go และ command line แต่ละตัวอย่างแสดงการลบข้อมูลซ้ำโดยรักษาลำดับและจัดการการคำนึงตัวพิมพ์
JavaScript
const text = `apple
banana
apple
Cherry
banana
cherry`
// Remove exact duplicates, preserve order
const unique = [...new Map(
text.split('\n').map(line => [line, line])
).values()].join('\n')
// → "apple\nbanana\nCherry\ncherry"
// Case-insensitive deduplication
const seen = new Set()
const ciUnique = text.split('\n').filter(line => {
const key = line.toLowerCase()
if (seen.has(key)) return false
seen.add(key)
return true
}).join('\n')
// → "apple\nbanana\nCherry"
// Trim whitespace before comparing
const trimDedup = text.split('\n').filter(line => {
const key = line.trim().toLowerCase()
if (seen.has(key)) return false
seen.add(key)
return true
}).join('\n')
Python
text = """apple
banana
apple
Cherry
banana
cherry"""
lines = text.splitlines()
# Remove duplicates, preserve order (Python 3.7+)
unique = list(dict.fromkeys(lines))
# → ['apple', 'banana', 'Cherry', 'cherry']
# Case-insensitive deduplication
seen = set()
ci_unique = []
for line in lines:
key = line.lower()
if key not in seen:
seen.add(key)
ci_unique.append(line)
# → ['apple', 'banana', 'Cherry']
# With whitespace trimming
seen = set()
trimmed = []
for line in lines:
key = line.strip().lower()
if key not in seen:
seen.add(key)
trimmed.append(line)
Go
package main
import (
"fmt"
"strings"
)
func removeDuplicates(text string) string {
lines := strings.Split(text, "\n")
seen := make(map[string]bool)
result := make([]string, 0, len(lines))
for _, line := range lines {
if !seen[line] {
seen[line] = true
result = append(result, line)
}
}
return strings.Join(result, "\n")
}
func main() {
text := "apple\nbanana\napple\ncherry\nbanana"
fmt.Println(removeDuplicates(text))
// → apple\nbanana\ncherry
}
CLI (bash)
# Remove duplicates (sorts output — does not preserve order)
sort -u file.txt
# Remove duplicates while preserving original order
awk '!seen[$0]++' file.txt
# Case-insensitive dedup, preserve order
awk 'BEGIN{IGNORECASE=1} !seen[tolower($0)]++' file.txt
# Trim whitespace then dedup
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' file.txt | awk '!seen[$0]++'
# Count duplicates before removing
sort file.txt | uniq -c | sort -rn