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 -gt 0 ]
do
        read -p "输入数组的第$i个元数:"array[$i]
        let i++
        let num--
done
for i in ${!array[@]}
do
    echo "$i     ${array[$i]}"
done

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

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

要求使用for来完成

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

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

#!/bin/bash
>/tmp/file2    #清空文件内容
declare -A array1  #定义数组
ls -l $line |awk -F"."'{print $NF}'>/tmp/file2
while read line
do
        let array1[$line]++
done </tmp/file1
for i in ${!array1[@]}  #数组元素索引
do
        echo -e "$i\t${array1[$i]}"
done             

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

#!/bin/bash
>/tmp/file1     #清空文件内容
ls -l /etc |egrep '^-' |awk '{print $NF}' > /tmp/file1 
declare -A array2  #定义数组
while read line
do
        let array2[$line]++
done </tmp/file1
for i in ${!array2[@]}   #数组元素索引
do
        echo -e "$i\t${array2[$i]}"
done

6、统计一个存放姓名和性别的文件中不同性别的个数
7、统计不同tcp连接的状态的数量

猜你喜欢

转载自blog.csdn.net/qq_42989565/article/details/82227911