关联数组——按扩展名统计指定目录中文件的数量

一、脚本说明

#!/bin/bash
#****************************************************
#Date:        2020-06-25
#Author:      Damon Ye
#FileName:   ExtensionName.sh
#Description:$1 indicates the Folder_Path
#****************************************************
declare -A Array
ls $1 | sed 's/ /
/g' >> $1/FileName.txt  每个文件名作为单独的1行,保存在FileName.txt中,以便于处理
while read FileName 
 do
   ArrayIndex=${FileName##*.}          贪婪匹配能更准确的找到扩展名。相反,非贪婪匹配能更准确的找到文件名。
   let Array[$ArrayIndex]++
 done < $1/FileName.txt
for i in ${!Array[@]}
  do
    echo "$i :::::: ${Array[$i]}"
  done
rm -f $1/FileName.txt         

二、执行结果

[root@localhost package]# bash ExtensionName.sh  ./test
mp3 :::::: 2
txt :::::: 3
doc :::::: 4
png :::::: 6

三、贪婪匹配——匹配最长的部分

#!/bin/bash
#****************************************************
#Date:        2020-06-25
#Author:      Damon Ye
#FileName:   GreedyMatch.sh
#Description:#匹配方向:从左到右   %匹配方向:从右到左
#****************************************************
filename=1a.2bb.3ccc.txt
echo -e "The filename is "$filename""
echo ${filename##*.}      最佳匹配 for 扩展名                                                                                                                                                                   
echo ${filename#*.}
echo ${filename%.*}      最佳匹配 for 文件名
echo ${filename%%.*}


[root@localhost package]# bash GreedyMatch.sh 
The filename is "1a.2bb.3ccc.txt"
txt
2bb.3ccc.txt
1a.2bb.3ccc
1a
             

 四、发散扩展——basename和dirname

[root@localhost test]# pwd
/tmp/test/package/test
[root@localhost test]# basename /tmp/test/package/test    提取路径最后的文件名
test
[root@localhost test]# dirname /tmp/test/package/test     提取路径前面的目录名
/tmp/test/package
[root@localhost test]#
dirname /tmp/test/package/test/file1.sh /tmp/test/package/test [root@localhost test]# basename /tmp/test/package/test/file1.sh file1.sh [root@localhost test]#
原文地址:https://www.cnblogs.com/ytdyz/p/13192266.html