shell数组

shell数组

普通数组:只能使用整数作为数组索引(元素的下标)
关联数组:可以使用字符串作为数组索引(元素的下标)

普通数组定义:

用括号来表示数组,数组元素(变量)用“空格”符号分割开。定义数组的一般形式为:

一次赋一个值:

变量名=变量值

stu_list2[0]=罗兴林
stu_list2[3]=李文杰
stu_list2[4]=王仁刚
stu_list2[6]=陈亮亮
stu_list2[9]=郑家强

一次赋多个值:

array1=(`cat /etc/passwd`)			//将文件中每一行赋值给array1数组
array2=(`ls /root`)
array3=(harry amy jack "Miss Hou")
array4=(1 2 3 4 "hello world" [10]=linux)
stu_list1=(罗兴林 李文杰 王仁刚 叶金阳  郑家强)
不制定索引号,直接定义,bash会自动索引标号,默认补上 0 1 2 3 4

读取普通数组:

${array[i]} i表示元素的下标

echo ${array[@]:1:2}	访问指定的元素;1代表从下标为1的元素开始获取;2代表获取后面几个元素
提取出李文杰: # echo ${stu_list2[3]} 
增加数组中的一个元素: # stu_list2[5]='于谦'
删除数组中的一个元素: # unset stu_list2[5]
修改数组中的一个元素:# stu_list2[4]='柳岩'

直接获取普通数组的所有元素值:echo ${stu_list2[@]} 或者 echo ${stu_list2[*]}
罗兴林 李文杰 柳岩 陈亮亮 郑家强

获取数组元素个数(长度):echo ${#stu_list2[@]}
5
取出所有索引标号:echo ${!stu_list2[@]}
0 3 4 6 9

查看普通数组信息:

declare -a|grep stu_list2
set|grep stu_list2

关联数组定义:

关联数组使用名称(通常是字符串,但某些语言中支持其它类型)作为索引,是key/value模式的结构,key是索引,value是对应元素的值。

首先声明关联数组

delcaer -A 关联数组名
declare -A asso_array1
declare -A stu_info

一次赋一个值:

数组名[索引|下标]=变量值

stu_info["小于"]="一百八十斤的运维"
stu_info[小李]="体育运动全满分的运维"
stu_info[小罗]="精通贵州文化的运维"

一次赋多个值:

asso_array2=([name1]=harry [name2]=jack [name3]=amy [name4]="Miss Hou")

查看关联数组:

declare -A
declare -A |grep stu_info
set|grep stu_info

读取关联数组

根据key,提取value
echo ${stu_info[小李]}
体育运动全满分的运维

增加关联数组的元素
stu_info[小张]="善于思考的运维"

删除关联数组的元素
unset stu_info[小张]

修改关联数组的元素
stu_info[小李]="卷王之王"

提取关联数组所有元素
echo ${stu_info[@]}或者echo ${stu_info[*]}
一百八十斤的运维 精通贵州文化的运维 体育运动全满分的运维

提取关联数组中所有的key
echo ${!stu_info[@]}
小于 小罗 小李 

获取数组所有元素个数
echo ${#stu_info[*]} 
3

遍历普通数组

#!/bin/bash
stus=(于超 罗兴林 张鑫 郑佳强)

# 语法1,直接提取所有元素
for res in ${stus[@]}
do
    echo $res
done

echo "-------"

# 语法2,提取所有索引,然后再取值
for index in ${!stus[@]}
do
    echo ${stus[${index}]}
done

遍历关联数组

#!/bin/bash
declare -A stu_info
stu_info=([name]="小李" [age]="23" [sex]="男" [job]="运维")
# 语法1
for i in ${!stu_info[@]}
do 
echo ${stu_info[$i]}
don
echo "-------"
# 语法2
for i in ${stu_info[@]}
do 
echo $i
done

使用数组,实现对nginx进行日志统计分析

# 脚本实现的效率较低
#!/bin/bash

declare -A ip_count
exec < y-awk-nginx.log
while read line
do
    remote_ip=$(echo $line | awk '{print $1}')
    # 直接累加赋值
    let ip_count[$remote_ip]++
    # 写法一个意思
    # ip_count[$remote_ip]=$[ ip_count[$remote_ip] + 1]
done

for key in ${!ip_count[@]}
do
    echo -e "该IP: {$key}    出现的次数是:${ip_count[$key]}"
done
# awk实现的效率很高,50万行数据只执行了0.2s
# time是统计执行的时间的命令,user	0m0.201s,即表示执行了0.2s
time awk '{ip_count[$1]++}END{for(key in ip_count) print "ip是"key",出现的次数是"ip_count[key]}' y-awk-nginx.log
posted @ 2023-09-21 16:08  村尚chun叔  阅读(17)  评论(0编辑  收藏  举报