概述
如果大家熟悉java的话,遍历文件夹然后检索相关信息可能比较简单,基本有现成的资料,修修补补就好了。今天主要讲怎么用shell来遍历目标文件夹和所有文件并统计相关信息。
需求
编写一个shell脚本来查看目标文件夹下所有的file和directory,并且打印出他们的绝对路径。
运行command:./showdir.sh input_path output_result
思路:
BFS遍历,数据结构为queue,数组实现
测试环境准备
[oracle@nwppdb:/home/oracle]$mkdir -p test/test1/test11/test111[oracle@nwppdb:/home/oracle]$mkdir -p test/test2/test22 [oracle@nwppdb:/home/oracle]$echo 123>test/1.txt [oracle@nwppdb:/home/oracle]$echo 123>test/2.txt[oracle@nwppdb:/home/oracle]$echo 123>test/test1/3.txt[oracle@nwppdb:/home/oracle]$echo 123>test/test1/test11/4.txt[oracle@nwppdb:/home/oracle]$echo 123>test/test1/test11/5.txt[oracle@nwppdb:/home/oracle]$echo 123>test/test2/6.txt [oracle@nwppdb:/home/oracle]$echo 123>test/test2/test22/7.txt[oracle@nwppdb:/home/oracle]$echo 123>test/test2/test22/8.txt
![94b0991a07449d66d07633c134b1b82b.png](https://img-blog.csdnimg.cn/img_convert/94b0991a07449d66d07633c134b1b82b.png)
脚本实现:
[oracle@nwppdb:/home/oracle]$cat showdir.sh #!/bin/bashSAVEIFS=$IFSIFS=$(echo -en "b") #处理特殊字符文件名queue[0]="head"path_[0]=''head_index=0 #head = the first inde - 1tail_index=1 #tail=length the last index + 1head="null"dir_count=0file_count=0path=``#if the output directory is not exist, make a new directory#处理目标文件所处地址不存在问题out_path=$2e_path=""while [ ${out_path##*/} != ${out_path%%/*} ]do dir_name=${out_path%%/*} if [ ! -e $e_path""$dir_name ] then mkdir $e_path""$dir_name fi e_path=$e_path""$dir_name"/" out_path=${out_path#*/}donetouch $2#use queue to take BFSfunction enQueue(){ #insert into tail queue[${tail_index}]=$1 path_[${tail_index}]=$path"/"$1 tail_index=$((${tail_index}+1))}function deQueue(){ #dequeue from head head_index=$((${head_index}+1)) head=${queue[head_index]}}#start of this programenQueue $1while [ ${head_index} -ne $((${tail_index}-1)) ]dodeQueuepath_[1]=`pwd`"/"$1path=${path_[$head_index]}echo "["${head}"]" >>$2for var in `ls ${path_[$head_index]}`doif [ -d $path"/""${var}" ]thendir_count=$((${dir_count}+1))enQueue $varfiecho $path"/""${var}" >>$2file_count=$((${file_count}+1))doneecho "" >>$2donefile_count=$((${file_count}-${dir_count}))echo "[Directories Count]:"${dir_count} >>$2echo "[Files Count]:"$file_count >>$2IFS=$SAVEIFS
![e8de06ec96586a995664fc16a1435e17.png](https://img-blog.csdnimg.cn/img_convert/e8de06ec96586a995664fc16a1435e17.png)
![46e8930506b44847211876f64e0aabd6.png](https://img-blog.csdnimg.cn/img_convert/46e8930506b44847211876f64e0aabd6.png)
测试脚本
cd /home/oracle./showdir.sh test showdir.md
![c7c9ae8a6d7b86a7df8073aa47f5bd53.png](https://img-blog.csdnimg.cn/img_convert/c7c9ae8a6d7b86a7df8073aa47f5bd53.png)
篇幅有限,用shell去遍历的内容就介绍到这了,大家有空也可以自己测试下。
后面会分享更多关于devops和DBA方面内容,感兴趣的朋友可以关注下!!
![fc42584df83a637159f36556f681f2e5.gif](https://img-blog.csdnimg.cn/img_convert/fc42584df83a637159f36556f681f2e5.gif)