我開始研究一些sh的實作,當我試圖對一些檔案夾中的檔案做一些操作時,我遇到了一些麻煩。
情況如下:
我在兩個不同的子檔案夾內有一個 TXT 檔案串列。
我有一個TXT檔案的串列,在兩個不同的子檔案夾中:
├──檔案夾A
├───隨機檔案1.txt
├────隨機檔案2.txt
├── 檔案夾B
├── File1.txt
├── 檔案夾C
├─── File2.txt
根據檔案所在的檔案夾,我應該采取一個特定的行動。
obs1:檔案夾A的檔案不應該被處理。
基本上,我嘗試了兩種不同的方法:
第一種:
files_b="$incoming/$origin"/FolderB/*.txt
files_c="$incoming/$origin"/FolderC/*.txt
if [ "$(ls -A $files_b)" ]; then
for file in $files_b.
do
#take action[/span
done #take action
else
echo -e "33[1;33mWarning: 沒有檔案33[0m"
fi -e
if [ "$(ls -A $files_c)" ] ; then
for file in $files_c.
do
#take action[/span
done #take action
else
echo -e "33[1;33mWarning。沒有檔案33[0m"
fi
這個問題是,當我運行命令ls -A時,如果其中一個檔案夾(B或C)是空的,它會拋出一個錯誤,因為在路徑的最后有 "*.txt"。
第二個問題:
path="$incoming/$origin"/span>/*.txt
find $path -type f -name "*. while read txt; do
for filein $txt
do
name=$(basename "$file"/span>)
dir=$(basename $(dirname $file)
if [ "$dir" ==FolderB]; then# Do something to files"/span>
elif [ "$dir"/span> == FolderC]; then
# Do something to files"/span>
fi
done
done done
對于這種方法,問題是我要從檔案夾A中挑選檔案,而我不希望這樣做(因為這樣做會因為 "if "陳述句而降低性能),而且我不知道如何使用查找命令來驗證該檔案夾是否為空。
有人能幫助我嗎?
謝謝大家。
謝謝大家。
uj5u.com熱心網友回復:
我將這樣寫代碼:
- 沒有未參考的引數
- 不使用未參考的引數擴展 不要使用
- 使用
printf而不是echo.
ls來檢查目錄是否為空。
# You cannot safely expand a parameter so that it does file globbing。
# 但不**到分詞。把glob直接放在回圈中。
# 或者使用一個陣列。。
shopt -s nullglob
found=
for file in "$incoming/$origin"/span>/FolderB/*. txt; do.
do
發現=1
#take action
done
if [ "$found"/span> ]; then
printf "33[1;33mWarning: 沒有檔案33[0m
"
fi
uj5u.com熱心網友回復:
在第一個解決方案中,你可以簡單地隱藏錯誤資訊。
if [ "$(ls -A $files_b 2> /dev/null)]; then
在第二個解決方案中,在子目錄而不是父目錄啟動find:
path="$incoming/$origin/FolderA $incoming/$origin/FolderB"
uj5u.com熱心網友回復:
我認為使用find應該更好
files_b="${incoming}/${origin}/FolderB"
files_c="${incoming}/${origin}/FolderC"
find files_b -name "*.txt" -exec action1 {} ;
find files_b -name "*.txt" -exec action2 {} 。
或者甚至只是找到
查找 "${incoming}/${origin}/FolderB"/span> -name "*. txt" -exec action1 {} ;
找到 "${incoming}/${origin}/FolderC" -name "*. txt" -exec action2 {} 。
當然,你應該考慮你的行動,但你可以制作接受檔案名的函式或獨立腳本
。轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/324961.html
標籤:
