如何递归遍历一个目录树,只找文件? [英] How to recursively traverse a directory tree and find only files?

查看:104
本文介绍了如何递归遍历一个目录树,只找文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个 scp 调用以下载远程系统上存在的文件夹。下载的文件夹有子文件夹,在这些子文件夹中有一堆文件,我想作为参数传递给python脚本,如下所示:

I am working on a scp call to download a folder present on a remote system. Downloaded folder has subfolders and within these subfolders there are a bunch of files which I want to pass as arguments to a python script like this:

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

我添加了查找是否有任何目录并排除它们的逻辑。但是,我不递归地遍历这些目录。

I have added the logic to find if there are any directories and excluding them. However, I don't traverse down those directories recursively.

下面的部分结果:

File downloaded succesfully
Running BD scanner
It is a directory
It is a directory
It is a directory
Exiting

我想改进这个代码,以便遍历所有目录并选取所有文件。请帮助我任何建议。

I want to improve this code so that it traverses all directories and picks up all files. Please help me with any suggestions.

推荐答案

您可以使用 shopt -s globstar 在Bash 4.0 +:

You can use shopt -s globstar in Bash 4.0+:

#!/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

Bash手册说这个关于 globstar

Bash manual says this about globstar:


如果设置,文件扩展上下文中使用的模式**将
匹配所有文件和零个或多个目录,子目录。如果
的模式后跟一个'/',只有目录和子目录
匹配。

If set, the pattern ‘**’ used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a ‘/’, only directories and subdirectories match.

更多 globstar 在这里讨论: https://unix.stackexchange。 com / questions / 117826 / bash-globstar-matching

这篇关于如何递归遍历一个目录树,只找文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆