原文链接: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 阅读(2994) 
评论(1)  编辑  收藏  所属分类: 
linux/unix