shell的数组操作

来源:互联网 发布:编程语言好学吗 编辑:程序博客网 时间:2024/05/17 01:23
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

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  (这样也可以)
0 0