簡體   English   中英

如何遞歸遍歷目錄樹並只查找文件?

[英]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討論: httpsglobstar

為什么要經歷使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM