How can I print only those lines that appear exactly once in a file? E.g., given this file:
mountain
forest
mountain
eagle
The output would be this, because the line mountain
appears twice:
forest
eagle
- The lines can be sorted, if necessary.
Using awk:
You almost had the answer in your question:
sort filename | uniq -u
Use
sort
anduniq
:The
-u
option would causeuniq
to print only unique lines. Quoting fromman uniq
:For your input, it'd produce:
Obs: Remember to
sort
beforeuniq -u
becauseuniq
operates on adjacent lines. So whatuniq -u
actually does is to print lines that don't have identical neighbor lines, but that doesn't mean they are really unique. When yousort
, all the identical lines get grouped together and only the lines that are really unique in the file will remain afteruniq -u
.