Risposte:
Riesci a convivere con un elenco alfabetico e ordinato:
echo "red apple
> green apple
> green apple
> orange
> orange
> orange
> " | sort -u
?
green apple
orange
red apple
o
sort -u FILE
-u sta per unico e l'unicità viene raggiunta solo tramite l'ordinamento.
Una soluzione che preserva l'ordine:
echo "red apple
green apple
green apple
orange
orange
orange
" | { old=""; while read line ; do if [[ $line != $old ]]; then echo $line; old=$line; fi ; done }
red apple
green apple
orange
e, con un file
cat file | {
old=""
while read line
do
if [[ $line != $old ]]
then
echo $line
old=$line
fi
done }
Gli ultimi due rimuovono solo i duplicati, che seguono immediatamente, il che si adatta al tuo esempio.
echo "red apple
green apple
lila banana
green apple
" ...
Stamperà due mele, divise da una banana.
Per ottenere solo un conteggio:
$> egrep -o '\w+' fruits.txt | sort | uniq -c
3 apple
2 green
1 oragen
2 orange
1 red
Per ottenere un conteggio ordinato:
$> egrep -o '\w+' fruits.txt | sort | uniq -c | sort -nk1
1 oragen
1 red
2 green
2 orange
3 apple
MODIFICARE
Aha, questo NON era lungo i confini delle parole, colpa mia. Ecco il comando da usare per le righe complete:
$> cat fruits.txt | sort | uniq -c | sort -nk1
1 oragen
1 red apple
2 green apple
2 orange
Ecco un semplice script Python che utilizza il tipo Counter . Il vantaggio è che ciò non richiede l'ordinamento del file, essenzialmente utilizzando memoria zero:
import collections
import fileinput
import json
print(json.dumps(collections.Counter(map(str.strip, fileinput.input())), indent=2))
Produzione:
$ cat filename | python3 script.py
{
"red apple": 1,
"green apple": 2,
"orange": 3
}
oppure puoi usare un semplice one-liner:
$ cat filename | python3 -c 'print(__import__("json").dumps(__import__("collections").Counter(map(str.strip, __import__("fileinput").input())), indent=2))'
-d
nota.