Bash
自動將文件一個一個移動到一個目錄,並且僅在目標文件夾為空時
是否可以?並按字母倒序排列?
本質上,這是:如何通過類型遞歸地將文件從目錄及其子目錄移動到另一個目錄?
除了每個文件都不會移動到目標目錄*,除非*一個單獨的程序已獲取該目標目錄中的唯一文件並將其移動到其他位置(因此目標文件夾是空的並且“準備好”將下一個文件移動到那裡)。
你想要這樣的東西嗎?
#!/usr/bin/env bash ## This is the target path, the directory ## you want to copy to. target="some/path with/spaces"; ## Find all files and folders in the current directory, sort ## them reverse alphabetically and iterate through them find . -maxdepth 1 -type f | sort -r | while IFS= read -r file; do ## Set the counter back to 0 for each file counter=0; ## The counter will be 0 until the file is moved while [ $counter -eq 0 ]; do ## If the directory has no files if find "$target" -maxdepth 0 -empty | read; then ## Move the current file to $target and increment ## the counter. mv -v "$file" "$target" && counter=1; else ## Uncomment the line below for debugging # echo "Directory not empty: $(find "$target" -mindepth 1)" ## Wait for one second. This avoids spamming ## the system with multiple requests. sleep 1; fi; done; done
該腳本將一直執行,直到所有文件都被複製。如果目標為空,它只會將文件複製到
$target
其中,因此它將永遠掛起,除非另一個程序在文件進入時將其刪除。
$target
如果您的文件或文件名包含換行符 ( ) ,它將中斷,\n
但空格和其他奇怪字元應該沒問題。