[awk] Remove duplicate lines while keeping input order

Created on November 30, 2026

Use an associative array to record how often each line appears. Start with this fruits.txt file.

apple
orange
apple
banana
orange
awk '!line_counts[$0]++' fruits.txt
apple
orange
banana

line_counts is a name chosen for this example. Each key is the full line, $0. The post-increment returns zero on the first occurrence, so the negation is true and awk prints the line. Later occurrences have a nonzero count and are skipped.

awk Shell command