shell里如何查看当前目录下文件(如何用shell脚本来查看目标文件夹下所有的file和directory)

概述

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

shell里如何查看当前目录下文件(如何用shell脚本来查看目标文件夹下所有的file和directory)(1)


脚本实现:

[oracle@nwppdb:/home/oracle]$cat showdir.sh #!/bin/bash SAVEIFS=$IFS IFS=$(echo -en "\n\b") #处理特殊字符文件名 queue[0]="head" path_[0]='' head_index=0 #head = the first inde - 1 tail_index=1 #tail=length the last index 1 head="null" dir_count=0 file_count=0 path=`` #if the output directory is not exist, make a new directory #处理目标文件所处地址不存在问题 out_path=$2 e_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#*/} done touch $2 #use queue to take BFS function 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 program enQueue $1 while [ ${head_index} -ne $((${tail_index}-1)) ] do deQueue path_[1]=`pwd`"/"$1 path=${path_[$head_index]} echo "["${head}"]" >>$2 for var in `ls ${path_[$head_index]}` do if [ -d $path"/""${var}" ] then dir_count=$((${dir_count} 1)) enQueue $var fi echo $path"/""${var}" >>$2 file_count=$((${file_count} 1)) done echo "" >>$2 done file_count=$((${file_count}-${dir_count})) echo "[Directories Count]:"${dir_count} >>$2 echo "[Files Count]:"$file_count >>$2 IFS=$SAVEIFS

shell里如何查看当前目录下文件(如何用shell脚本来查看目标文件夹下所有的file和directory)(2)

shell里如何查看当前目录下文件(如何用shell脚本来查看目标文件夹下所有的file和directory)(3)


测试脚本

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

shell里如何查看当前目录下文件(如何用shell脚本来查看目标文件夹下所有的file和directory)(4)


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

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

shell里如何查看当前目录下文件(如何用shell脚本来查看目标文件夹下所有的file和directory)(5)

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页