要求:写一个linux bash脚本来查看目标文件夹下所有的file和directory,并且打印出他们的绝对路径。
运行command:./mydir.sh input_path output_result
要求输出格式为:
代码思路:
bfs遍历,数据结构为queue,数组实现。
代码实现:
#!/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,总结了一些解决方法,放在了另一篇里。
如对本文有疑问, 点击进行留言回复!!
linux下文本编辑器vim的使用方法(复制、粘贴、替换、行号、撤销、多文件操作)
网友评论