【操作系统作业—lab1】linux shell脚本 遍历目标文件夹和所有文件 | 包括特殊字符文件名的处理 - Go语言中文社区

【操作系统作业—lab1】linux shell脚本 遍历目标文件夹和所有文件 | 包括特殊字符文件名的处理


要求:写一个linux bash脚本来查看目标文件夹下所有的file和directory,并且打印出他们的绝对路径。

运行command:./myDir.sh  input_path  output_result

要求输出格式为

 

 

代码思路:

BFS遍历,数据结构为queue,数组实现。

代码实现:

#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "nb")  #处理特殊字符文件名


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,总结了一些解决方法,放在了另一篇随笔里。

 



版权声明:本文来源博客园,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.cnblogs.com/dallywang/p/10486287.html
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-11-10 10:06:50
  • 阅读 ( 1170 )
  • 分类:Linux

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢