shell脚本 之数组

1、读取/etc/hosts文件,将文件中的每一行作为一个元数赋值给数组

#!/bin/bash
IFS='$ \n'
while  read line
do
        arry= `echo $line |awk '{print $1}'`
done < /etc/hosts
for i in ${!arry[@]}
do
    echo "$i     ${arry[$i]}"
done
IFS='$ \t\n'

2、使用read读入创建数组元数的个数,且元数也由用户自己输入,要求使用while来完成

#!/bin/bash
i=1
read -p "请输入要创建数组元数的个数:" num
while [ $num -ge $i ]
do
        read -p "输入数组的第$i个元数:"array[$i]
        let i++        
done
for j in ${!array[@]}
do
    echo "$j     ${array[$j]}"
done

3、使用read读入创建数组元数的个数,且元数也由用户自己输入,要求使用until来完成

#!/bin/bash
i=1
read -p "请输入要创建数组元数的个数:" num
until [ $i -gt $num ]
do
        read -p "输入数组的第$i个元数:"array[$i]
        let i++
done
for j in ${!array[@]}
do
    echo "$j     ${array[$j]}"
done

要求使用for来完成

#!/bin/bash
read -p "请输入要创建数组元数的个数: " num
for i in `seq $num`
do
read -p "输入数组的第$i个元数: " array02[$i]
done
for j in ${!array02[@]}
do
    echo "$j     ${array02[$j]}"
done

4、使用数组的方式统计某一目录下不同的文件后缀的数量

 #!/bin/bash
declare -A file_count
while read file 
do
    suffix=${file##*.}
    let file_count[$suffix]++
done <<< "$(find $1 -type f)" #等价于 done <<< "`find $1 -type f`"
for i in ${!file_count[@]}
do
    echo "文件$i的数量是: ${file_count[$i]}"
done       

5、使用数组的方式统计某一目录下的普通文件的不同类型的数量,例如:ASCII text的数量,UTF-8
Unicode text的数量,ASCII English text的数量等


#!/bin/bash
#filename: filestat.sh
if [ $# -ne 1 ]; then
    echo "Usage `basename $0` DIR "
    exit 1
fi
declare -A typecount
while read line
do
    filetype=`file -b $line |awk '{print $NF}'`
    let typecount[$filetype]++
done <<< "`find $1 -type f -print`"

echo "========== File types and counts =========="

for i in ${!typecount[@]}
do
    echo "$i ${typecount[$i]}"
done            

6、统计一个存放姓名和性别的文件中不同性别的个数

[root@gaojingbo shell]# cat name_sex.txt 
jack    F
nammd   M
sanmd   F
脚本
#!/bin/bash
declare -A sexcount
while read line
do
    sextype=`echo $line |awk '{print $2}'`
    let sexcount[$sextype]++
done < ./name_sex.txt

echo "========== sex counts =========="

for i in ${!sexcount[@]}
do
    echo "$i ${sexcount[$i]}"
done

7、统计不同tcp连接的状态的数量

#!/bin/bash
OFS=$IFS
IFS='
'
declare -A statecount
for line in  `ss -ant |grep -vi state`
do
    type=`echo $line |awk '{print $1}'`
    let statecount[$type]++
done


for i in ${!statecount[@]}
do
    echo "$i ${statecount[$i]}"
done
IFS=$OFS
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值