zoukankan      html  css  js  c++  java
  • shell数组

    1、数组分类

    普通数组:只能使用整数 作为数组索引 
    关联数组:可以使用字符串 作为数组索引
    

    2、普通数组

    1.方式一, 对每个索引赋值
    #数组名[索引]=变量值
    # array1[0]=pear
    # array1[1]=apple
    
    2.方式二, 一次赋多个值
    #数组名=(多个变量值)
    # array1=(tom jack alice)
    # array2=(`cat /etc/passwd`)
    # array3=(tom jack alice "bash shell")
    # array4=(1 2 3 "linux shell" [20]=puppet)
    
    3.查看数组赋值
    # declare -a
    # declare -A
    
    4.访问数组中的元数
    # echo ${array1[0]}        访问数组第一个索引的值
    # echo ${array1[@]}        访问数组中所有索引的值,== ${array1[*]}
    # echo ${!array1[*]}       访问数组所有的索引
    # echo ${#array1[@]}       统计数组元数的个数
    

    3、关联数组 

    1.定义关联数组
    # declare -A tt_array_1
    # declare -A tt_array_2
    
    2.方式一, 针对每个索引进行赋值
    #数组名[索引]=变量值 
    # tt_array1[index1]=pear
    # tt_array1[index2]=apple
    
    3.方式三, 一次赋多个值
    # tt_array2=([index1]=tom [index2]='bash shell')
    
    4.查看关联数组
    # declare -A
    
    5.访问数据元数
    # echo ${tt_array2[index2]}      访问数组第二个索引的值
    # echo ${tt_array2[@]}           访问数组所有索引的值 == ${array1[*]}
    # echo ${!tt_array2[@]}          访问数组所有的索引
    

    4、遍历数组

    遍历数组:推荐通过数组的索引,不推荐通过数组索引的个数。
    
    1.数组赋值与遍历示例
    # vim read.sh
    declare -A x                    定义关联数组
    while  read y                   循环读取文件每行,y=每行内容
    do
       let x[$y]++                  x='([a]="1" [b]="2" [c]="3" )' y=[a b c] 值=次数
       declare -A
    done <a.txt        
    
    for i in ${!x[*]}                循环数组的下标
    do
     echo "$i  ${x[$i]}"             i=下标  x[$i]=下标的值
    done
      
    
    
    2.统计日志访问量
    # vim tongji.sh       
    declare -A x
    file=$1                
    
    while  read y                      读取每行
    do
    ip=`echo $y |awk '{print $1}'`     取每行第一列
       let x[$ip]++                    x='([192.168.1.1]="3" [192.168.2.1]]="6" [192.168.3.1]="9" )'
    done<$file
    
    for i in ${!x[*]}                  循环数组的下标
    do
     echo "$i  ${x[$i]}"               i=下标  x[$i]=下标的值
    done
    
    3.统计ip连接数
    # vim connect.sh 
    declare -A x             
    y=`ss -an|awk '{print $1}'`        监听状态
    for i in $y                        读取每行
    do
            let x[$i]++                x=([LISTEN]=3 [ESTABLISHED]=6 [TIME_WAIT]=9)
    done
    
    for z in ${!x[@]}                  循环数组的下标
    do
            echo "$z ${x[$z]}"         z=下标  x[$z]=下标的值
    done

    5、awk 数组

    # ss -an | awk '/9000/{x[$1]++}END{for(i in x)print i,x[i]}'
                    匹配   行数组       数组下标       下标 值
    

                                       

                   

     

  • 相关阅读:
    关于apache的动态与静态编译
    使用awk处理正则表达式时注意事项
    fedora下apache默认配置
    vim显示行号、语法高亮、自动缩进的设置
    简单介绍apahce内存管理机制
    处理路径上的小技巧
    Educational Codeforces Round 80 (Rated for Div. 2)
    web前端页面性能优化小结
    web标准—可用性、可维护性、可访问性
    雅虎团队经验:网站页面性能优化的 34条黄金守则
  • 原文地址:https://www.cnblogs.com/wuhg/p/13410536.html
Copyright © 2011-2022 走看看