實用腳本:遍歷目標文件夾和所有文件

概述

如果大家熟悉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/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
實用腳本:遍歷目標文件夾和所有文件 | 包括特殊字符文件名處理

實用腳本:遍歷目標文件夾和所有文件 | 包括特殊字符文件名處理


測試腳本

cd /home/oracle
./showdir.sh test showdir.md
實用腳本:遍歷目標文件夾和所有文件 | 包括特殊字符文件名處理


篇幅有限,用shell去遍歷的內容就介紹到這了,大家有空也可以自己測試下。

後面會分享更多關於devops和DBA方面內容,感興趣的朋友可以關注下!!

實用腳本:遍歷目標文件夾和所有文件 | 包括特殊字符文件名處理


分享到:


相關文章: