shell中數組操作
1.將一個字符串按照指定分隔符轉換成數組
在shell處理中,經常需要將一個字符串按照字符串中的某個分隔符轉換成一個數組,從而方便處理,轉換時需要環境變量IFS,指定分隔符類型:
#!/bin/bash
# test.sh
# 給定字符串,以 ; 進行分割
TEST_STR="abc;def;ghi;jkl"
# 備份之前的分隔符環境變量
OLD_IFS=$IFS
# 指定分隔符為 ;
IFS=";"
# 將字符串以 ; 分割成數組
STR_LIST=($TEST_STR)
# 恢復分隔符環境變量
IFS=$OLD_IFS
# 數組大小
echo "arry size: ${#STR_LIST[@]}"
# 數組內容
echo "arry content: ${STR_LIST[@]}"
$./test.sh
arry size: 4
arry content: abc def ghi jkl
2.判斷數組中是否包含某字符串
#!/bin/bash
# test.sh
# 給定字符串,以 ; 進行分割
item_arry=($1)
# 擴展給定數組的所有索引值
for i in ${!item_arry[@]};
do
if [ "${item_arry[$i]}" == "abc" ]; then
echo "abc is in arry"
fi
done
$./test.sh "abc def ghi jkl"
abc is in arry
3.判斷數組內是否有重復元素
由於沒有找到對應的操作,借助awk實現判斷數組內是否有重復元素:
#!/bin/bash
# test.sh
# 將輸入參數轉為數組
item_arry=($1)
# 遍歷數組元素
for i in ${item_arry[@]}; do
echo $i
done | awk '{a[$1]++}END{for(i in a) {print a[i] ,i}}' | awk '$1>1{print $2" imte is duplicate";exit 1}'
# 判斷awk的返回值,為1則有重復元素
if [ $? -ne 0 ]; then
echo "item is duplicate"
else
echo "item is unique"
fi
$./test.sh "abc def ghi jkl"
item is unique
$./test.sh "abcd def ghi jkl abcd"
abcd imte is duplicate
item is duplicate