shell中的数组操作
2015-08-31 16:29
501 查看
1.数组定义,shell使用一对括号表示数组,数组元素间用”空格”分隔
# 空数组arr1 arr1=() # 数组arr2,成员分别是1, 2, 3, 4, 5, 6 arr2=(1 2 3 4 5 6)
2.数组元素读取,格式:${数组名[下标]},下标从0开始,下标为*或@代表整个数组内容
[root@10 ~]# echo ${arr2[0]} 1 [root@10 ~]# echo ${arr2[*]} 1 2 3 4 5 6
3.遍历数组, foreach
for num in ${arr2[*]}; do echo $num; done;
4.数组长度,格式:${#数组名[*或@]}
[root@10 ~]# echo ${#arr2[*]} 6
5.赋值,格式:数组名[下标]=值,如果下标不存在,则新增数组元素; 下标已有,则覆盖值
[root@10 ~]# arr2[6]=7 [root@10 ~]# echo ${arr2[*]} 1 2 3 4 5 6 7 [root@10 ~]# arr2[0]=-1 [root@10 ~]# echo ${arr2[*]} -1 2 3 4 5 6 7
6.分片,格式:${数组名[*或@]:起始位:长度},截取部分数组,返回字符串,中间用空格分隔;将结果使用“()”,则得到新的切片数组
[root@10 ~]# echo ${arr2[*]:0:3} -1 2 3 [root@10 ~]# arr3=(${arr2[*]:0:3}) [root@10 ~]# echo ${arr3[*]} -1 2 3
7.替换元素,格式:${数组名[*或@]/查找字符/替换字符}, 不会修改原数组;如需修改的数组,将结果使用“()”赋给新数组
[root@10 ~]# echo ${arr2[*]} -1 2 3 4 5 6 7 [root@10 ~]# echo ${arr2[*]/7/10} -1 2 3 4 5 6 10 [root@10 ~]# arr4=(${arr2[*]/7/10}) [root@10 ~]# echo ${arr4[*]} -1 2 3 4 5 6 10
8.删除数组,格式:unset 数组,清除整个数组; unset 数组[下标],清除单个元素
[root@10 ~]# echo ${arr2[*]} -1 2 3 4 5 6 7 [root@10 ~]# unset arr2[0] [root@10 ~]# echo ${arr2[*]} 2 3 4 5 6 7 [root@10 ~]# unset arr2 [root@10 ~]# echo ${arr2[*]} [root@10 ~]#
相关文章推荐
- .bash_profile 配置
- Win7怎么打开Windows PowerShell窗口?Win7打开Windows PowerShell窗口的方法介绍
- ShellExecuteEx调用第三方程序
- shell 编程 if for while 循环体语法
- Linux-《Linux命令行与shell脚本编程大全》阅读笔记
- Shell Tips
- Linux系统命令及Shell脚本学习笔记五:字符处理
- linux shell 字符串操作详解 (长度,读取,替换,截取,连接,对比,删除,位置 )
- Linux 的shell 字符串截取很有用。有八种方法。
- Bash 下如何逐行读取一个文件
- SylixOS Shell使用
- Shell文件操作符(> >> >>>)
- [Shell]Bash变量:变量测试与内容替换
- [Shell]Bash变量:数值运算及运算符
- Linux_bash特性详解(技巧)
- shell中的多进程【并发】
- Linux目录结构、bash的基础特性、I/O重定向及管道
- linux 的shell处理两Excel的比较方法
- shell脚本那点事儿6
- shell展开