sed is actually seductive

Candy Shop / Disco Inferno

Candy Shop / Disco Inferno

Why I failed.

Yesterday I was trying to implement array_unique compliant on shellscript. The attempt failed, but this morning I found out the reason why it didn't work. The answer is the difference between BSD sed command and GNU sed command. Both sed command treat white space and newline differently. What I meant by that is

echo -e "AK47\nM16\nM14\nAA12" | sed 's/\s/\n/g'

will work fine on GNU sed, but it doesn't work on BSD sed. Instead you should write like

echo -e "AK47\nM16\nM14\nAA12" | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g'

Finally, we get array_unique compliant on shellscript.

# Non-unique array
Array=(AK47 M16 MP5 MP5 M16 AK47 AA12)
# This will work on both BSD sed and GNU sed.
ArrayUnique=$(echo ${Array[@]} | sed $'s/ /\\\n/g' | sort | uniq | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g')