[英]How to recursively traverse a directory tree and find only files?
我正在进行scp
调用以下载远程系统上的文件夹。 下载的文件夹有子文件夹,在这些子文件夹中有一堆文件我想作为参数传递给python脚本,如下所示:
scp -r researcher@192.168.150.4: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
我想改进这个代码,以便它遍历所有目录并获取所有文件。 请帮助我任何建议。
你可以在Bash 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
Bash手册说这个:
如果设置,则文件名扩展上下文中使用的模式“**”将匹配所有文件以及零个或多个目录和子目录。 如果模式后跟'/',则只有目录和子目录匹配。
这里有更多的globstar
讨论: https : globstar
为什么要经历使用globbing
进行文件匹配的麻烦,而是通过使用带有while循环的进程替换( <()
)来使用find
with。
#!/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扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.