I have come up with a convoluted way to remove duplicate numerical entries from a bash array and sort the results (i.e. creating a sorted set). I invite others to give a a better solution… but this works and that is what is important for a throwaway script:
seeds2=`echo -e ${seeds[@]}| awk '{if (!x[$1]++) print $1"\\\\n\\n"}'`; unset seeds; seeds=( `echo -e $seeds2 | sort -bg` )
where $seeds is the array to sort – with each entry ending in a “\n”… awk needs inputs line by line (as does uniq, but remember uniq is only for removing adjacent repeating lines).



9 comments ↓
Joel, you are one sick, sick puppy!
I just used bash to make this script:
if test -x some_file ; then exec some_file ; else exec some_other_file ; fi
I put the first semi-colon after the ‘then’ which of course leads to an incredibly value error message. And so I waste 5-10 minutes just getting an if statement to work!
Every time I come back to bash/sh I have forgotten the syntax and I am reminded how I hate shell scripting with a passion!
I hope for the sake of our children that shell scripting is buried in the future.
i initially was just using bash to run replications of a stochastic simulation, but then it got more convulted and I’ve had to learn alot of bash stuff. The Advanced Bash scripting guide is my friend
oh and instead of “test” you can just do:
if [ -x some_file ]; then …
Yeah I found out about the [ ] thing after using an embedded system that had ‘[' as a symlink but it wouldn't handle ']‘. So now I always use test instead of hiding behind those braces…
ah, fair enough!
Uuuh….
I live in a giant bucket…?
My spoon is too big!
I am a banana!
Hmm I also noticed I wrote ‘value’ instead of ‘vague’. ‘Value’ is one of those words I type so much in code that my fingers type it without even noticing.
Hi. I came across this post while searching for a solution and I finally came up with this:
UNIQUE_ELEMENTS=”`for ELEMENT in ${ARRAY[@]}; do echo ${ELEMENT}; done | sort -u`”
Thanks Peter! Much more elegant
Leave a Comment