2012-02-13 45 views
0

有什麼不對下面的表達式:達到極限後,也條件沒有得到真正的

... 
if [ $i -ge ${tLen} ]; then 
    echo "Maximum limit reached, i=$i" 
fi 
i=$(($i+1)) 
... 

這個說法while循環中。 i是計數器變量,其初始值爲0. tLen存儲數組的長度,我正在遍歷的數組。 即使i達到tLen,此條件仍未獲得true。我哪裏錯了?

這是我的完整代碼:

read filename 
words=(5 2) 
i=0 
sed 's/ /\n/g' "$filename" >"tmp.txt" 
while read word 
do 
    words[i]=$word 
    i=$(($i+1)) 
    awk "/$word/ {count += 1} END{print count}" "tmp.txt" >>"tmp2.dat" 
done <"tmp.txt" 
i=0 
tLen=${#words[@]} 
echo "Length of words: ${tLen}" 
declare -A wordMap 
while read count 
do 
    if [ $i -ge ${tLen} ]; then 
    echo "Maximum length reached, i=$i" 
    break 
    fi 
    wordMap["${words[$i]}"]=$count 
    i=$(($i+1)) 
done <"tmp2.dat" 

rm "tmp.txt" 
rm "tmp2.dat" 

其實我試圖計算給定文本中的每個詞的出現次數...

+0

請發表您的其他代碼。這可能會導致[subshel​​l問題](http://mywiki.wooledge.org/BashPitfalls#grep_foo_bar_.7C_while_read_-r.3B_do_.28.28count.2B-.2B-.29.29.3B_done) – l0b0 2012-02-13 09:29:03

+0

適用於我。嘗試在第一行使用'#!/ bin/bash -xv'運行以查看變量中的內容。 – choroba 2012-02-13 09:50:41

+0

我得到錯誤'壞數組下標'是什麼意思? – batman 2012-02-13 09:53:29

回答

0

該代碼對於文本中有空行或單詞之間有多個空格是有問題的。在這種情況下,因爲${words[$i]}是空行

wordMap["${words[$i]}"]=$count 

會失敗,並bad array subscript消息。

0

這不是一個答案,「真實」的問題,但如果你只是想在文件中實際地計數單詞:

sed 's/[[:space:][:punct:]]/\n/g;' < testfil | sed '/^$/d' | sort -f | uniq -ci | sort -n 

似乎工作。

我不能明顯地看到你的代碼中的錯誤,否則,特別是在最小的例子中。嘗試在代碼的早期插入調試echo語句或設置set -x以獲得模擬行爲的最小示例。