說明:shell中數組的下標默認是從0開始的
1、將字符串放在數組中,獲取其長度
for ((i=0; i<$length; i++))
do
echo ${array[$i]}
done
執行結果:
[oracle@99bill-as9 array]$ sh length.sh
4
a
--n
d
2)、打印字符串:
2、字符串用其他字符分割時
str2="a#b#c"
a=($(echo $str2 | tr '#' ' ' | tr -s ' '))
length=${#a[@]}
for ((i=0; i<$length; i++))
do
echo ${a[$i]}
done
#echo ${a[2]}
執行結果:
a
c
3、數組的其他操作
#ouput the first array element直接輸出的是數組的第一個元素
echo $array
#Use subscript way access array用下標的方式訪問數組元素
echo ${array[1]}
#Output the array輸出這個數組
echo ${array[@]}
#Output in the array subscript for 3 the length of the element輸出數組中下標為3的元素的長度
echo ${#array[3]}
#Output in the array subscript 1 to 3 element輸出數組中下標為1到3的元素
echo ${array[@]:1:3}
#Output in the array subscript greater than 2 elements輸出數組中下標大于2的元素
echo ${array[@]:2}
#Output in the array subscript less than 2 elements輸出數組中下標小于2的元素
echo ${array[@]::2}
4、遍歷訪問一個字符串(默認是以空格分開的,當字符串是以其他分隔符分開時可以參考2)
5、如何使用echo輸出一個字符串str="-n". 由于-n是echo的一個參數,所以一般的方法echo "$str"是無法輸出的.
解決方法可以有:
新聞熱點
疑難解答