2

Im new to bash scripting... Im trying to sort and store unique values from an array into another array. eg:

list=('a','b','b','b','c','c');

I need,

unique_sorted_list=('b','c','a')

I tried a couple of things, didnt help me ..

sorted_ids=($(for v in "${ids[@]}"; do echo "$v";done| sort| uniq| xargs))

or

sorted_ids=$(echo "${ids[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' ')

Can you guys please help me in this ....

3
  • Take the | xargs out of your first try. Commented Feb 14, 2015 at 5:23
  • hi kevin , tried that .. but I see no difference.. Commented Feb 14, 2015 at 5:28
  • @kevin . I understood now ...everythings fine...it sorts as (a b c) but I need (b c a) since it has b is three times c 2times and a once.. That is the question i intended to ask Commented Feb 14, 2015 at 6:26

2 Answers 2

2

Try:

$ list=(a b b b c c)
$ unique_sorted_list=($(printf "%s\n" "${list[@]}" | sort -u))
$ echo "${unique_sorted_list[@]}"
a b c

Update based on comments:

$ uniq=($(printf "%s\n" "${list[@]}" | sort | uniq -c | sort -rnk1 | awk '{ print $2 }'))
Sign up to request clarification or add additional context in comments.

7 Comments

Hi Jaypal , your case works, But :-( in my case it is ('a','a','a','b','b','b') not (a a a b b b b b) ....Because of the quotes it takes each value to be unique and prints the same array ...I guess
actually my array contains user names of files...This is how I get it
for file in $fList; do dList+="$(ls -lt $file | awk '{ print $3 }')" done ------- from dList I need to get sorted , unique array
@Karthik In bash the array elements are separated by a space.
@jayapal..thanks I understand this.. but when I do the command "for file in $flist.." given in my previous comment and when I do echo $dList it prints the names without any space ...thats the problem..
|
1

The accepted answer doesn't work if array elements contain spaces.

Try this instead:

readarray -t unique_sorted_list < <( printf "%s\n" "${list[@]}" | sort -u )

In Bash, readarray is an alias to the built-in mapfile command. See help mapfile for details.

The -t option is to remove the trailing newline (used in printf) from each line read.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.