echo "red apple
> green apple
> green apple
> orange
> orange
> orange
> " | sort -u
?
green apple
orange
red apple
或者
sort -u FILE
U 代表唯一性,唯一性只有通过排序才能达到。
一种保持顺序的解决方案:
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
还有一份文件
cat file | {
old=""
while read line
do
if [[ $line != $old ]]
then
echo $line
old=$line
fi
done }
最后两个只删除重复项,重复项紧随其后——这符合您的示例。
echo "red apple
green apple
lila banana
green apple
" ...