龙空技术网

如何用shell脚本来查看目标文件夹下所有的file和directory

波波说运维 181

前言:

此时看官们对“java 目录下所有文件”大体比较关怀,朋友们都想要分析一些“java 目录下所有文件”的相关资讯。那么小编同时在网络上网罗了一些有关“java 目录下所有文件””的相关文章,希望小伙伴们能喜欢,同学们快快来学习一下吧!

概述

如果大家熟悉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
脚本实现:
[oracle@nwppdb:/home/oracle]$cat showdir.sh #!/bin/bashSAVEIFS=$IFSIFS=$(echo -en "\n\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
测试脚本
cd /home/oracle./showdir.sh test showdir.md

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

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

标签: #java 目录下所有文件