各位好, 我寫了一支 shell script, 目的在搜尋現行目錄所有 ".txt" 檔內的字串.
若 ".txt" 檔有我要的字串, 就把該字串的整行輸出到 result.txt. 因為我要搜尋字
串有很多, 就先把字串都寫入 strings.txt, 再用迴圈一個個的搜尋.
##################### 以下是我的 shell script ################################
string=`cat strings.txt`
for file_name in `ls -F | grep ".txt"`
do
if [ $file_name != "strings.txt" ] && [ $file_name != "result.txt" ]
then
for name in $string
do
grep -w $name $file_name >> result.txt
done
fi
done
##################### 以上是我的 shell script ################################
但我後來發現, 這樣的寫法很沒有效率. 假設共有 5 個字串在 strings.txt 中,
則根據以上 script 的邏輯, 每個檔案都要被我搜尋 5 次去一一的找出每一個字串.
請問各位, 我該如何去改進這一點? 讓我的程式更有效率.
--
All Comments