我是 bash 新手(但不是編程新手)。我有一個 bash 腳本,用于查找.txt專案中的所有檔案
for i in `find . -name "*.txt"`;
do
basename= "${i}"
cp ${basename} ./dest
done
但是,我只想從特定的子目錄中獲取 .txt 檔案。例如,這是我的專案結構:
project/
├── controllers/
│ ├── a/
│ │ ├── src/
│ │ │ ├── xxx
│ │ │ └── xxx
│ │ └── files/
│ │ ├── abc.txt
│ │ └── xxxx
│ └── b/
│ ├── src/
│ │ ├── xxx
│ │ └── xxx
│ └── files/
│ ├── abcd.txt
│ └── xxxx
├── lib
└── tests
我只想從和獲取.txt檔案。我嘗試用 替換,它作業正常,但在 GitHub 操作上出現錯誤。因此,我正在尋找一種更強大的方法來從子目錄中查找檔案,而無需在 for 回圈中對路徑進行硬編碼。那可能嗎?controllers/a/filescontrollers/b/filesfind . -name "*.txt"find ./controllers/*/files/*txtNo such file or directory found.txt
uj5u.com熱心網友回復:
您可以對搜索目錄使用大括號擴展,例如
find ./project/controllers/{a,b} -type f -name "*.txt"
僅選擇下面的檔案./project/controllers/a和./project/controllers/b
此外,您basename的腳本中將不再需要使用 (并使用符號' '右側的(空格)來解決錯誤。傳統上,在 bash 中,您將使用行程替換來提供回圈而不是使用回圈,例如'='whilefor
while read -r fname; do
# basename="${fname}" # note! no ' ' on either side of =
cp -ua "$fname" ./dest
done < <(find ./project/controllers/{a,b} -type f -name "*.txt")
基于許多路徑的評論進行編輯
如果您有很多controllers不只是aand b,那么使用-path選項而不是-name選項可以提供解決方案,例如
find . -path "./project/controllers/*/files/*.txt" -type f
將選擇".txt"下面controllers包含files目錄的任何目錄下的任何檔案。
uj5u.com熱心網友回復:
在我看來,您需要的是一個簡單的cp命令,
cp project/controllers/*/files/*.txt ./dest/
如果您只想復制.txt目錄下擴展名為的檔案files(而不是在其子目錄中,如果有的話)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/532258.html
