Search code examples
arraysbashunique

Keeping only the unique elements in an array Bash


I have an array that contains the following:

67A 
257B 
67C 
257D

I want to keep only the unique numbers, meaning I want my array to contain 67A and 257B. How would I do this in a Bash script?


Solution

  • One way to do it would be to create a new array with the unique numbered values which will take the first of each numeric prefix found. Say your values are in the indexed-array array. You could do:

    new_array=( $(printf "%s\n" ${array[@]} | sort -n -u) )
    

    Above you are just using the command-substitution of printf (used to output each element on a separate line) piped to sort -n -u (which sorts numerically unique). You use the results to populate new_array.

    Now new_array would contain:

    67A
    257B