【问题标题】:How to recursively traverse a directory tree and find only files?如何递归遍历目录树并仅查找文件?
【发布时间】:2017-06-07 14:01:32
【问题描述】:

我正在处理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 file directory


    【解决方案1】:

    你可以在 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
    

    Bash 手册中提到了 globstar

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

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

    【讨论】:

      【解决方案2】:

      为什么要麻烦使用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 扩展。

      【讨论】:

      • 为什么使用while/read 循环来解析find 的输出(并使用非标准功能)而不是使用find-exec 开关? :).
      • 如果目录有大量文件并且每个文件执行的函数很慢,那么使用find会创建一个大管道文件或消耗大量内存。
      猜你喜欢
      • 2013-03-04
      • 2016-08-25
      • 2015-05-18
      • 2018-07-12
      • 2014-03-11
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 2021-02-26
      相关资源
      最近更新 更多