日期:2014-05-16  浏览次数:20736 次

Linux数组,去掉重复的数值

#!/bin/sh 
 
array=("java" "linux" "c" "linux" "c++" "java") 
len=${#array[@]} 
for((i=0;i<$len;i++)) 
do 
  for((j=$len-1;j>i;j--)) 
  do 
    if [[ ${array[i]} = ${array[j]} ]];then 
      unset array[i] 
    fi 
  done 
done 
 
for arr in ${array[@]} 
do 
  echo $arr 
done 


[root@bogon shell]# ./array1.sh

c

linux

c++

java


以上代码,处理后的数组,如果用下标来访问数组元素,不一定准确。所以,后来将处理完后的数组元素值,重新赋给新的数组了。如下:

array1=("nbi_db" "information_schema" "mysql" "performance_schema" "test" "nbi_db")
length=${#array1[@]}
for  (( i=0; i<$length; i++ )); do
  for (( j=$(expr $length - 1); j>$i; j-- ));do
    if [[ "${array1[$i]}" = "${array1[$j]}" ]];then
      unset array1[$i]
    fi
  done
done

echo "array1 for ... in--------------"
index=0
for arr in ${array1[@]}
do
  echo "[$index] "$arr
  ((index++))
done

echo
echo "array1 for iterator------------"
for ((index=0;index<$length;index++))
do
  echo "[$index] "${array1[$index]}
done

echo

index=0
for arr in ${array1[@]};do
  array2[$index]=$arr
  ((index++))
done

echo
length=${#array2[@]}
for ((index=0;index<$length;index++))
do
  echo "array2[$index]="${array2[$index]}
done


运行结果:
array1 for ... in--------------
[0] information_schema
[1] mysql
[2] performance_schema
[3] test
[4] nbi_db

array1 for iterator------------
[0]
[1] information_schema
[2] mysql
[3] performance_schema
[4] test
[5] nbi_db


array2[0]=information_schema
array2[1]=mysql
array2[2]=performance_schema
array2[3]=test
array2[4]=nbi_db