2012-08-05 74 views
0

腳本我有一個劇本我在bash寫了一個小錯誤,我無法找出什麼是我做錯了誤差在bash

請注意,我用這個腳本千計算這個錯誤只發生了幾次(像20左右),但它仍然發生了

腳本的作用是這樣的:基本上它需要輸入一個網站,我從一個網站用實用程序w3m和它統計其中的單詞的所有出現次數......在它們從最常見的單詞到它們僅出現一次的單號之後

這是代碼:

#!/bin/bash 
# counts the numbers of words from specific sites      # 
# writes in a file the occurrences ordered from the most common   # 

touch check   # file used to analyze the occurrences 
touch distribution  # final file ordered 

page=$1    # the web page that needs to be analyzed 
occurrences=$2   # temporary file for the occurrences 
dictionary=$3      # dictionary used for another purpose (ignore this) 

# write the words one by column 
cat $page | tr -c [:alnum:] "\n" | sed '/^$/d' > check 

# lopp to analyze the words 
cat check | while read words 
do 
    word=${words} 
    strlen=${#word} 
    # ignores blacklisted words or small ones 
    if ! grep -Fxq $word .blacklist && [ $strlen -gt 2 ] 
    then 
     # if the word isn't in the file 
     if [ `egrep -c -i "^$word: " $occurrences` -eq 0 ] 
     then 
      echo "$word: 1" | cat >> $occurrences 
     # else if it is already in the file, it calculates the occurrences 
     else 
      old=`awk -v words=$word -F": " '$1==words { print $2 }' $occurrences` 
        ### HERE IS THE ERROR, EITHER THE LET OR THE SED ### 
      let "new=old+1" 
      sed -i "s/^$word: $old$/$word: $new/g" $occurrences 
     fi 
    fi 
done 

# orders the words 
awk -F": " '{print $2" "$1}' $occurrences | sort -rn | awk -F" " '{print $2": "$1}' > distribution 

# ignore this, not important 
grep -w "1" distribution | awk -F ":" '{print $1}' > temp_dictionary 

for line in `cat temp_dictionary` 
do 
    if ! grep -Fxq $line $dictionary 
    then 
     echo $line >> $dictionary 
    fi 
done 

rm check 
rm temp_dictionary 

這是錯誤:(我翻譯它,所以它可以在英文不同)

./wordOccurrences line:30 let:x // where x is a number, usually 9 or 10 (but also 11, 13, etc) 
1: syntax error in the espression (the error token is 1) 
sed: expression -e #1, character y: command 's' not terminated // where y is another number (this one is also usually 9 or 10) with y being different from x 

編輯: 與千電子伏說話的時候,看起來就像是一個換行符問題

我在let和sed之間添加了一個回顯來打印sed,它在5到10分鐘內完美工作,直到出現錯誤。通常情況下,sed的沒有錯誤是這樣的:

S/^ CONSULENTI:$ 6/CONSULENTI:7/g的

但是當我得到了它是這樣的錯誤:

S/^ 00145: 1 1 $/00145:4/g

如何解決這個問題?

回答

2

如果你在$ old中得到一個新行,這意味着awk會打印兩行,所以在$ occurence中有一個重複項。

該腳本似乎很複雜的計算單詞,並沒有效率,因爲它啓動循環中的許多進程和處理文件; 也許你可以做同樣的事情與

sort | uniq -c 
1

你也應該考慮到你的情況不敏感是不是整個程序是一致的。我創建了一個只有「foooo」的頁面並運行程序,然後創建一個帶有「Foooo」的程序並再次運行該程序。 'old =`awk ...'行將'old'設置爲空字符串,因爲awk匹配大小寫敏感。這導致文件沒有被更新。隨後的sed和可能的一些greps也是區分大小寫的。

這可能不是唯一的錯誤,因爲它並不能解釋您看到的錯誤消息,但它是一個跡象表明大小寫不同的同一個詞會被你的腳本錯誤處理。

下將分離的話,小寫它們,然後刪除那些小於三個大字:

tr -cs '[:alnum:]' '\n' <foo | tr '[:upper:]' '[:lower:]' | egrep -v '^.{0,2}$' 

在腳本前使用,這將意味着在腳本的其餘部分不會有不區分大小寫是正確的。