如何递归遍历目录树并仅查找文件?
问题描述:
我正在致电scp
来下载远程系统上存在的文件夹。下载文件夹有子文件夹和这些子文件夹内有文件的一群,我想作为参数传递给一个Python脚本是这样的:如何递归遍历目录树并仅查找文件?
scp -r [email protected]:SomeName/SomeNameElse/$folder_name/ $folder_name/
echo "File downloaded successfully"
echo "Running BD scanner"
for d in $folder_name/*; do
if [[ -d $d ]]; then
echo "It is a directory"
elif [[ -f $d ]]; then
echo "It is a file"
echo "Running the scanner :"
python bd_scanner_new.py /home/nsadmin/Some/bash_script_run_files/$d
else
echo "$d is invalid file"
exit 1
fi
done
我已经添加了逻辑来寻找是否有任何目录,不包括他们。但是,我不会递归地遍历这些目录。下面
部分结果:
File downloaded succesfully
Running BD scanner
It is a directory
It is a directory
It is a directory
Exiting
我想提高这个代码,以便它遍历所有目录,拿起所有文件。请帮助我提出任何建议。
答
为什么要通过使用globbing
来进行文件匹配,而是使用find
来解决这个问题,这是通过使用具有while循环的进程替换(<()
)来实现的。
#!/bin/bash
while IFS= read -r -d '' file; do
# single filename is in $file
python bd_scanner_new.py "$file"
done < <(find "$folder_name" -type f -print0)
这里,find
做下面的子目录中的任何水平执行递归搜索从提到的路径中的所有文件。文件名可以包含空格,制表符,空格,换行符。要以安全的方式处理文件名,请使用-print0
进行查找:使用所有控制字符打印文件名&以NUL结尾,然后是read
具有相同除限制字符的命令进程。
注意;在附注中,请始终在bash
中双引号变量以避免shell的扩展。
答
可以在击4.0+使用shopt -s globstar
:
#!/bin/bash
shopt -s globstar nullglob
cd _your_base_dir
for file in **/*; do
# will loop for all the regular files across the entire tree
# files with white spaces or other special characters are gracefully handled
python bd_scanner_new.py "$file"
done
猛砸手册说,这大约globstar
:
如果设置,模式 '**' 在一个文件名扩展上下文中使用会 匹配所有文件和零个或多个目录和子目录。如果 该模式后面跟有'/',则只有目录和子目录 匹配。
更多globstar
这里的讨论:https://unix.stackexchange.com/questions/117826/bash-globstar-matching
为什么要用'while' /'read'循环解析find'(和使用非标准功能)的'输出,而不是使用'find'的'-exec'开关? ':)'。 –