原文鏈接:http://bbs.linuxtone.org/thread-5317-1-1.html IT運維專家網--"自由平等,互助分享!"
shell中數組的下標默認是從0開始的
1. 將字符串存放在數組中,獲取其長度
#!/bin/bash
str="a b --n d"
array=($str)
length=${#array[@]}
echo $length
for ((i=0; i<$length; i++))
do
echo ${array[$i]}
done
along@along-laptop:~/code/shell/shell/mycat/testfile$ ./test.sh
4
a
b
--n
d
打印字符串:
[root@mc2 tmp]# cat test.sh
#!/bin/bash
str="a b c"
for i in $str
do
echo $i
done
[root@mc2 tmp]# cat array.sh
#!/bin/bash
str="a b c"
array=($str)
for ((i=0;i<${#array[@]};i++))
do
echo ${array[$i]}
done
結果:
a
b
c
2. 字符串用其他字符分隔時
#!/bin/bash
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]}
along@along-laptop:~/code/shell/shell/mycat/testfile$ ./test.sh
a
b
c
3. 數組的其他操作
#!/bin/bash
str="a b --n dd"
array=($str)
length=${#array[@]}
#直接輸出的是數組的第一個元素
echo $array
#用下標的方式訪問數組元素
echo ${array[1]}
#輸出這個數組
echo ${array[@]}
#輸出數組中下標為3的元素的長度
echo ${#array[3]}
#輸出數組中下標為1到3的元素
echo ${array[@]:1:3}
#輸出數組中下標大于2的元素
echo ${array[@]:2}
#輸出數組中下標小于2的元素
echo ${array[@]::2}
along@along-laptop:~/code/shell/shell/mycat/testfile$ ./test.sh
a
b
a b --n dd
2
b --n dd
--n dd
a b
4. 遍歷訪問一個字符串(默認是以空格分開的,當字符串是由其他字符分隔時可以參考 2)
#!/bin/bash
str="a --m"
for i in $str
do
echo $i
done
along@along-laptop:~/code/shell/shell/mycat/testfile$ ./para_test.sh
a
--m
5. 如何用echo輸出一個 字符串str="-n". 由于-n是echo的一個參數,所以一般的方法echo "$str"是無法輸出的.
解決方法可以有:
echo x$str | sed 's/^x//'
echo -ne "$str\n"
echo -e "$str\n\c"
printf "%s\n" $str (這樣也可以) |
posted on 2010-03-31 15:28
xzc 閱讀(2985)
評論(1) 編輯 收藏 所屬分類:
linux/unix