c++遍历文件夹下的文件_实用脚本:遍历目标文件夹和所有文件 | 包括特殊字符文件名处理...

概述

如果大家熟悉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

脚本实现:

[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
46e8930506b44847211876f64e0aabd6.png

测试脚本

cd /home/oracle./showdir.sh test showdir.md
c7c9ae8a6d7b86a7df8073aa47f5bd53.png

篇幅有限,用shell去遍历的内容就介绍到这了,大家有空也可以自己测试下。

后面会分享更多关于devops和DBA方面内容,感兴趣的朋友可以关注下!!

fc42584df83a637159f36556f681f2e5.gif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值