บทความนี้อธิบายวิธีใช้คำสั่ง uniq ใน Linux เพื่อหาหรือกรองบรรทัดซ้ำในไฟล์ พร้อมตัวอย่างการใช้งาน
คำสั่ง uniq เป็นคำสั่งง่ายๆ ที่ output หรือ omit บรรทัดซ้ำใน input หรือไฟล์ที่ให้มา
ไวยากรณ์คำสั่ง uniq
ไวยากรณ์สำหรับคำสั่ง uniq มีดังนี้:
uniq OPTIONS INPUT OUTPUT
โปรดทราบว่า:
- OPTIONS คือรายการตัวเลือกจากตารางด้านล่าง
- INPUT ควรเป็น path ไปยังไฟล์ที่จะอ่าน
- *Standard input *ก็ใช้ได้
- OUTPUT ควรเป็นไฟล์ที่เก็บผลลัพธ์ของ uniq command
- หากไม่ระบุ standard output จะถูกใช้ (default พิมพ์ผลลัพธ์ไป console)
หากไม่กำหนด input หรือ output files คุณสามารถ redirect input และ output ไปมากับ uniq command ใช้ STDIN และ STDOUT – ดูบทความนี้สำหรับวิธีทำ
ตัวเลือก (Options)
ตารางด้านล่าง list ตัวเลือกทั่วไปจาก user manual:
| -c | Prefix lines ด้วยจำนวนครั้งที่เกิดขึ้น |
| -d | พิมพ์เฉพาะ duplicate lines หนึ่งต่อ group |
| -D | พิมพ์ duplicate lines ทั้งหมด |
| -i | Ignore case differences เมื่อเปรียบเทียบ |
| -s | หลีกเลี่ยงการเปรียบเทียบ N ตัวอักษรแรก |
| -u | พิมพ์เฉพาะ unique lines |
คุณสามารถดู user manual เต็มสำหรับคำสั่ง uniq โดยรัน:
man uniq
ตัวอย่างคำสั่ง uniq
ตัวอย่างไฟล์
ตัวอย่างต่อไปจะใช้ไฟล์ตัวอย่างต่อไปนี้เป็น input:
movies.txt
Dirty Harry Dirty Harry Total Recall Bride of Frankenstein Total Recall Demolition Man
Default Behaviour – ลบบรรทัดซ้ำ
โดย default คำสั่ง uniq จะลบบรรทัดซ้ำ
uniq movies.txt
ซึ่งจะ output:
Dirty Harry Total Recall Bride of Frankenstein Total Recall Demolition Man
โปรดทราบว่า บรรทัดซ้ำถูกลบ ไม่ใช่ duplicates ทั้งหมด เฉพาะ adjacent, identical lines เท่านั้นที่ถูกลบ
แสดงจำนวนครั้งที่ซ้ำ
ตัวเลือก -c จะเพิ่มจำนวนครั้งซ้ำหน้าบรรทัดแต่ละบรรทัด:
uniq -c movies.txt
ซึ่ง output:
2 Dirty Harry 1 Total Recall 1 Bride of Frankenstein 1 Total Recall 1 Demolition Man
แสดงเฉพาะบรรทัดที่ NOT ซ้ำ
ตัวเลือก -u จะแสดงเฉพาะบรรทัดที่ไม่ซ้ำ:
uniq -u movies.txt
ซึ่งจะ output:
Total Recall Bride of Frankenstein Total Recall Demolition Man
แสดงเฉพาะบรรทัดที่ ARE ซ้ำ
ตัวเลือก -d จะแสดงเฉพาะบรรทัดซ้ำ:
uniq -d movies.txt
ซึ่งจะ output:
Dirty Harry
อีกครั้ง – โปรดทราบว่า บรรทัดซ้ำถูกรวมหรือข้าม ไม่ใช่ duplicated lines เฉพาะ adjacent, identical lines เท่านั้นที่ถูกประมวลผลโดย uniq command!
บันทึกผลลัพธ์
ส่ง filename เป็นพารามิเตอร์สุดท้ายให้คำสั่ง เพื่อบันทึกผลลัพธ์ลงไฟล์นั้น:
uniq -d movies.txt duplicated.txt
ใช้ Standard Redirection
như กล่าวมา ไม่จำเป็นต้องส่ง input และ output files ให้ uniq command
Standard Redirection สามารถ direct output ของคำสั่งอื่นไป uniq ซึ่งจะ redirect output ของตัวเองไปโปรแกรมหรือไฟล์อื่นได้
cat movies.txt | uniq > output.txt
ในตัวอย่างข้างต้น cat command อ่านไฟล์ตัวอย่าง – และ output ของมันถูก piped ไป unique command คำสั่ง uniq แล้ว redirect output ไปไฟล์ด้วย operator >
ชัดเจนว่านี่ไม่ให้ฟังก์ชันเพิ่มเติมจากการส่ง path input/output files ตรงๆ แต่เป็นตัวอย่างชัดเจนของการ pipe/redirect output ระหว่างคำสั่ง