我想在我的 macosx 檔案系統中獲取檔案的所有實體并將它們復制到外部硬碟的單個檔案夾中。我在終端中撰寫了一行簡單的代碼,但是當我執行它時,目標檔案夾中只有一個檔案,它在每次找到時都會被替換。似乎在單個命令中使用的 $RANDOM 或 $(uuidgen) 僅回傳一個用于 find 命令的每次出現 {} 的值。有沒有辦法為 find 命令的每個結果獲取一個新值?謝謝你。
find . -iname test.txt -exec cp {} /Volumes/EXT/$(uuidgen) \;
要么
find . -iname test.txt -exec cp {} /Volumes/EXT/$RANDOM \;
uj5u.com熱心網友回復:
find . -iname test.txt -exec bash -c '
for i do
cp "$i" "/Volumes/EXT/$RANDOM"
done' _ {}
您可以使用-execwith 將多個檔案傳遞給 bash 回圈。您不能在單個-exec.
uj5u.com熱心網友回復:
這應該有效:
find ... -exec bash -c 'cp "$1" /Volumes/somewhere/$(uuidgen)' _ {} \;
感謝 dan 和 pjh 對評論的更正。
uj5u.com熱心網友回復:
如果你有 Bash 4.0 或更高版本,另一個選擇是:
shopt -s dotglob
shopt -s globstar
shopt -s nocaseglob
shopt -s nullglob
for testfile in **/test.txt; do
cp -- "$testfile" "/Volumes/EXT/$(uuidgen)"
done
shopt -s dotglob.使 glob 能夠匹配以(例如.dir/test.txt)開頭的檔案和目錄shopt -s globstar允許使用**以遞回方式通過目錄樹匹配路徑shopt -s nocaseglob導致 glob 以不區分大小寫的方式進行匹配(例如findoption-inamevs-name)shopt -s nullglob當沒有任何匹配項時使 glob 擴展為空(否則它們會擴展為 glob 模式本身,這在程式中幾乎從不有用)--incp -- ...防止以連字符(例如)開頭的路徑被-dir/test.txt(錯誤)視為“cp”的選項- 請注意,此代碼在 4.3 之前的 Bash 版本上可能會失敗,
**因為在擴展模式時(愚蠢地)遵循符號鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/429497.html
