下面代码统计某目录下所有的文件类型相对应的文件个数,代码如下:
[Bash shell] 纯文本查看 复制代码 #!/bin/bash
if [ $# -ne 1 ];
then
echo $0 you_ path;
echo
fi
path=$1
declare -A statarray;
while read line;
do
ftype=`file -b "$line" | cut -d, -f1`
#echo $ftype | grep "[0-9][0-9]-bit" &> /dev/null
#if [ $? -eq 0 ];
#then
# ftype=`echo $ftype | awk -F, '{print $1}'`
#fi
let statarray["$ftype"]++;
done< <(find $path -type f -print)
#echo ======================File types and counts======================
for ftype in "${!statarray[@]}";
do
echo $ftype : ${statarray["$ftype"]}
done
运行输出:$ ./stat.sh ./
Bourne-Again shell script text executable : 5
Vim swap file : 2
ELF 32-bit LSB executable : 1
ASCII text : 6
ASCII C program text : 3 在上面代码中,主要利用 find 命令在指定目录下查找相应文件,然后使用 file 命令获取文件类型,其中 file 命令的 -b 选项是一种简略的输出,它忽略了文件名,而只输出该文件的类型说明,然后将这些文件类型说明信息作为关联数组 的索引以便在循环读取中统计。
在循环读取中,需要注意 done< <(find $path -type f -print) 这种用法,它可以简写成下面的形式:while read line;
do something
done< filename 注意 (find $path -type f -print) 的前面也有一个 < 符号。
另外,对于可执行的 ELF 文件,file -b 会输出所有的详细信息,因此需要使用 cut 命令来进行截取。 |