2017-03-16 223 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"