Removing duplicates on a variable without sorting

后端 未结 8 1023
陌清茗
陌清茗 2020-12-28 23:30

I have a variable that contains the following space separated entries.

variable=\"apple lemon papaya avocado lemon grapes papaya apple avocado mango banana\"         


        
相关标签:
8条回答
  • 2020-12-29 00:04

    In pure, portable sh:

    words="apple lemon papaya avocado lemon grapes papaya apple avocado mango banana"
    seen=
    for word in $words; do
      case $seen in
        $word\ * | *\ $word | *\ $word\ * | $word) 
          # already seen
          ;;
        *)
          seen="$seen $word"
          ;;
      esac
    done
    echo $seen
    
    0 讨论(0)
  • 2020-12-29 00:10

    This pipeline version works by preserving the original order:

    variable=$(echo "$variable" | tr ' ' '\n' | nl | sort -u -k2 | sort -n | cut -f2-)
    
    0 讨论(0)
提交回复
热议问题