2017-03-16 217 views
0

我在if語句行收到錯誤syntax error: invalid arithmetic operator (error token is ".txt")。我通過做echo $words_in_line來檢查words_in_line並輸出數字,所以我不明白爲什麼我得到這個錯誤。我該如何解決?語法錯誤:算術運算符無效(錯誤標記爲「.txt」)

#!/usr/bin/env bash 

#Outputs the lines that match wordcount range specified by min, $1, and max, $2 
function get_correct_lines_in_file() { 
    while read line ; do 
     words_in_line=$(echo "$line" | wc -w); 
     if [[ words_in_line -ge $1 ]] && [[ words_in_line -le $2 ]]; then #ERROR HERE 
      echo "$line" >> MARBLES.txt 
     fi 
    done < $1 
} 

#Check if $1 and $2 arguements exists- are NOT NULL 
if [[ "$1" != "" ]] && [[ "$2" != "" ]]; then 
    for i in ${*:3} 
    do 
     #If is a file you can read 
     if [[ -r $i && -f $i ]]; then 
      echo "$i exists and is readable" 
      get_correct_lines_in_file "$i" 
     #If file doesn't exist 
     elif [[ ! -f $i ]]; then 
      echo $i >> FAILED.log 
     fi 
    done 
fi 
+1

是'$ 1'和已知的數字'$ 2'?你可以修改你的代碼來演示(理想情況下,*證明*)他們是? –

+0

順便說一句,每次你想寫一行到它的時候打開'MARBLES.txt'輸出,並且在寫一行之後重新關閉它是相當低效的。將MARBLES.txt移動到循環結尾會更有效率,因此整個循環只重定向一次,而不是每個「echo」重定向一次。 –

+0

實際上,'<$ 1'表示你的'$ 1' **必須是**文件名,而不是數值。 –

回答

1

如果您希望您的函數中可以訪問最小值和最大值,則需要將它們傳遞給它們。考慮接受參數在你的函數,並明確通過傳遞函數的參數:

get_correct_lines_in_file() { 
    local -a words 
    while read -r -a words ; do 
     words_in_line=${#words[@]}; 
     if ((words_in_line >= $2)) && ((words_in_line <= $3)); then 
      printf '%s\n' "${words[*]}" 
     fi 
    done <"$1" >>MARBLES.txt 
} 

...後來,傳遞文件名是函數的$1,腳本的$1是函數的$2,和腳本的$2是函數的$3

get_correct_lines_in_file "$i" "$1" "$2"