If I have this array
arra[0]='Debian'
arra[1]='Debian'
arra[2]='Ubuntu'
arra[3]='Suse'
How can I stock in a new array Debian, Ubuntu and Suse only ? like this
new[0]='Debian'
new[1]='Ubuntu'
new[2]='Suse'
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Sign up to join this communityIf I have this array
arra[0]='Debian'
arra[1]='Debian'
arra[2]='Ubuntu'
arra[3]='Suse'
How can I stock in a new array Debian, Ubuntu and Suse only ? like this
new[0]='Debian'
new[1]='Ubuntu'
new[2]='Suse'
A working answer:
eval newArray=($(for i in "${arra[@]}" ; do echo "\"$i\"" ; done | sort -u))
It works with spaces in your array elements like in 'Red Hat'
: you need to print quote ""
around your variable value ("\"$i\"")
and eval
the result.
A more elegant alternative
eval newArray=($(printf "%q\n" "${arra[@]}" | sort -u))
where the format %q
is needed to quote the output of printf
.