Select records that occur exactly once with GNU uniq
Removing duplicate copies and selecting values that appear only once answer different questions. For a line-based import, uniq -u can identify IDs that have no repeated occurrence.
Run the example
Tested on Linux with GNU Bash 5.2.37, coreutils 9.7, grep 3.11 and diffutils 3.10. Use one Bash session and a text editor. Create a disposable working directory before saving the source:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save as demo_linux_uniq_single_occurrence_records.sh:
set -euo pipefail
export LC_ALL=C
records=$'blue\nred\nblue\ngreen\nred\nyellow'
printf 'One copy of every value:\n'
printf '%s\n' "$records" | sort -u
printf 'Values occurring once:\n'
printf '%s\n' "$records" | sort | uniq -u
printf 'Repeated values:\n'
printf '%s\n' "$records" | sort | uniq -dRun it:
bash demo_linux_uniq_single_occurrence_records.shObserved output:
One copy of every value:
blue
green
red
yellow
Values occurring once:
green
yellow
Repeated values:
blue
redsort -u retains one representative of every distinct line. Sorting without deduplication first lets uniq -u see the original counts and suppress entire repeated groups. uniq -d reports each repeated value once. Putting sort -u before uniq -u would erase the evidence of repetition.
Limits and input policy
The comparison here is exact and case-sensitive under the C locale. Each record occupies one line. Normalize only when the application defines equivalent values; case folding or trimming can combine previously distinct IDs. Sorting changes the original order, and uniq alone only compares adjacent records.
Clean up
Remove the saved script and the empty working directory in the same Bash session:
rm -- demo_linux_uniq_single_occurrence_records.sh
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its contents before removing anything else.
Reference
Acknowledgements
This post was created with assistance from AI.