brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: awk '!seen[$0]++' removes duplicate lines without sorting

Awk
~/tips/awk-dedupe

awk '!seen[$0]++' list.txt > unique.txt

Removes duplicate lines from a file and keeps the original order of the rest.

sort -u removes duplicates but also reorders the file. When the order matters, there is an awk one-liner that keeps the first copy of every line where it was.

awk '!seen[$0]++' list.txt > unique.txt

It works because seen[$0] counts how often a line has appeared. The first time the count is 0, ! makes that true, and awk prints the line. Then ++ raises the count, so every later copy is skipped.

Caveat: awk keeps every unique line in memory, so a file with hundreds of millions of lines can get heavy. And never write to the file you are reading from, or you end up with an empty file.

Further reading: GNU awk manual

More Awk tips echo 'cost: 1,50 and 2,25' | awk '{n=gsub(/,/,"."); print n": "$0}' awk -F, 'NR>1 {print > ($2".csv")}' data.csv echo 20261201 | awk '{print substr($0,1,4)"-"substr($0,5,2)"-"substr($0,7,2)}' echo '2.5 3.7' | awk '{print int($1), int($2), sprintf("%.0f", $1)}' echo 'web1:8080,5' | awk -F'[:,]' '{print $1, $2, $3}' All Awk tips (17) All topics

Link