Linux 脚本 —— 统计目录中文件的数量(按文件名分类)


说明

此脚本用于统计目录中不同文件名,各类文件的数量。比如: E9020_1111 与 E9020_2222是一类文件,但E9030_1111 与 E9030_2222又是另一类文件,统计其数量。

dir_list表示目录列表,static表示统计函数。

  1. 如果dir存在,且目录中有文件,则进行统计;
  2. 将统计信息保存在一个map[filename,count]中,其中key是文件名的前5个字符,value是文件数量。


脚本:

#!/bin/bash

# statistic some direcotrys


dir_list=(
#
# output
$HOME/data/rf_???/ok		## directories such as: /app/billapp/data/rf_001/ok、/app/billapp/data/rf_002/ok
$HOME/data/rf_???/err
)

# tmp_top
temp_dir="/tmp_top"

core_dir=(
#
# SG
$HOME/config/sg/sg_[AB][0-9][0-9]
)

decode_dir=(
#
)

if [ -n "$1" ] && [ "$1" = "decode" ]
then
    dir_list=(${decode_dir[@]})
fi

# Statistics the number of various filenames in the directory
function static {
	if [ $# -ne 1 ]
	then 
		return 1
	fi

    local directory=$1
	declare -A local mycount			# map[filename, count]

	contents=`ls -A $directory`
	for file in $contents
	do  
		if [ -f $directory/$file ]
		then
			mycount[${file:0:5}]=$[ ${mycount[${file:0:5}]} + 1 ]
		fi
	done
 
	for key in ${!mycount[@]}
	do
		echo "$key : ${mycount[$key]}"
	done
	
	return 0
}


for dir in ${dir_list[@]}
do	
    # If the directory exists and there are some files in the directory, then statistic.       
    if [ -d $dir ] && [ "`ls -l $dir | grep "^-" `" != "" ]
    then
        echo $dir
        static $dir
    	echo
    fi
    
    # if tmp_dir exists and is not empty, then statistic.
    if [ -d $dir$temp_dir ] && [  "`ls -A $dir$temp_dir`" != ""  ]
    then
        fileCounts=`find $dir$temp_dir -type f | wc -l`
        if [ $fileCounts -ne 0 ]    
        then
            echo "$dir$temp_dir : $fileCounts"
            echo 
        fi  
    fi 
done

# suport option : find core file
if [ -n "$1" ] && [ "$1" = "all" ]
then
    date

    for dir in ${core_dir[@]}
    do
        if [ -d $dir ]
        then
            fcounts=`find $dir -type f -name "core*" | wc -l`
            if [ $fcounts -ne 0 ]
            then
                echo "$dir core: $fcounts"
                echo
            fi
        fi
    done
fi

exit 0

你可能感兴趣的:(linux,命令,shell脚本,统计文件数量(按文件名分类))