• shell中一维数组值得获取


    (1)数组的定义

    root@tcx4440-03:~# a=(1 2 3 4)

    root@tcx4440-03:~# echo ${a[1]}
    2

    root@tcx4440-03:~# a[0]=1
    root@tcx4440-03:~# a[1]=2

    root@tcx4440-03:~# echo ${a[0]}
    1

    (2)数组值得获取

    root@tcx4440-03:~# var[0]=1
    root@tcx4440-03:~# var[1]=2

    root@tcx4440-03:~# echo $var[1]
    1[1]
    root@tcx4440-03:~# echo ${var[1]}
    2

    (3)获取数组的长度。用${#数组名[@或*]} 可以得到数组长度

    root@tcx4440-03:~# a=(10 20 30 40 50 60)
    root@tcx4440-03:~# echo ${#a[*]}
    6
    root@tcx4440-03:~# echo ${#a[@]}
    6

    root@tcx4440-03:~# echo ${a[@]}
    10 20 30 40 50 60

    root@tcx4440-03:~# echo ${a[*]}
    10 20 30 40 50 60

    (4)数组的读取,用${数组名[下标]} 下标是从0开始  下标是:*或者@ 得到整个数组内容
    root@tcx4440-03:~# echo ${a[1]}
    20

    root@tcx4440-03:~# echo ${a[*]}
    10 20 30 40 50 60

    (5)数组的赋值

    root@tcx4440-03:~# a[3]=100

    root@tcx4440-03:~# echo ${a[*]}
    10 20 30 100 50 60

    (6)数组的删除,直接通过:unset 数组[下标] 可以清除相应的元素,不带下标,清除整个数据。

    root@tcx4440-03:~# echo ${a[*]}
    10 20 30 100 50 60
    root@tcx4440-03:~# unset a[1]
    root@tcx4440-03:~# echo ${#a[@]}
    5

    root@tcx4440-03:~# echo ${a[*]}

    root@tcx4440-03:~# unset a
    root@tcx4440-03:~# echo ${#a[*]}
    0

    (7)分片使用,直接通过 ${数组名[@或*]:起始位置:长度} 切片原先数组,返回是字符串,中间用“空格”分开,因此如果加上”()”,将得到切片数组,上面例子:c 就是一个新数据。

    A:tt只是一个变量,不是一个数组,所以一定要加啊()

    root@tcx4440-03:~# tt=${a[*]:2:4}

    root@tcx4440-03:~# echo $tt 30 40 50 60

    root@tcx4440-03:~# echo ${tt[1]}

    root@tcx4440-03:~# echo ${tt[2]}

    B: c仍然是一个数组

    root@tcx4440-03:~# echo ${a[*]}
    10 20 30 40 50 60

    root@tcx4440-03:~# c=(${a[*]:1:4})

    root@tcx4440-03:~# echo ${c[*]}
    20 30 40 50
    root@tcx4440-03:~# echo $c
    20

    root@tcx4440-03:~# echo ${c[2]}
    40
    root@tcx4440-03:~# echo ${a[*]}
    10 20 30 40 50 60

    (8)替换,调用方法是:${数组名[@或*]/查找字符/替换字符} 该操作不会改变原先数组内容,如果需要修改,可以看上面例子,重新定义数据。

     root@tcx4440-03:~# echo ${a[*]}
    10 20 30 40 50 60
    root@tcx4440-03:~# echo ${a[*]/60/100}
    10 20 30 40 50 100

     root@tcx4440-03:~# echo ${a[*]}   //数组a的值是不变的
    10 20 30 40 50 60

    root@tcx4440-03:~# tt=${a[*]/100/1000}  //没有括号,则是一个变量,不是数组
    root@tcx4440-03:~# echo $tt
    10 20 30 40 50 60

    root@tcx4440-03:~# echo ${tt[1]}

    root@tcx4440-03:~# tt=(${a[*]/60/1000})  //有括号,则tt是一个数组

    root@tcx4440-03:~# echo ${tt[5]}

    1000

    root@tcx4440-03:~# echo ${tt[*]}
    10 20 30 40 50 1000
    root@tcx4440-03:~# echo ${a[*]}  //数组a是没有变化的
    10 20 30 40 50 60

  • 相关阅读:
    python 中 repr() 与str() 区别
    python高级特性 知识 架构总结
    python 递归 之加特技 汉诺塔
    python 递归 反转字符串
    git 的使用
    vim 常用命令
    ubuntu下零基础建站之python基础环境搭建
    Oracle 分组统计,抽取每组前十
    SQL Server2008知识点总结
    java 连接sql server2008配置
  • 原文地址:https://www.cnblogs.com/Berryxiong/p/4810607.html
Copyright © 2020-2023  润新知