遍历浮动数组以便在bash中进行比较

时间:2017-05-10 15:40:47

标签: bash shell awk linuxmint awk-formatting

我从csv文件中提取float列并存储在row_arr数组中。接下来我将sub_val中的存储值与数组元素进行比较。我想在变量中存储匹配元素的索引。我有以下代码和错误。

declare -a fileList=(
"file-a"
"file-b"
"file-c"
)

loc='../myData/'

file_name="sample.csv"
png='.png'
sep=', '
txt='.txt'

fileList_size="$(echo ${#fileList[@]})"

row_no=1
counter=0
counter2=0

for j in "${fileList[@]}"
do
        echo "Sub Row No = "$row_no
        #Picking value from 2nd column for other sample file
        sub_val=($(awk -F, 'FNR = "'"$row_no"'" {print $2}' $file_name))

        #### Storing Time Sequence in Array from Other File
        while IFS=, read -a csv_line;
        do 
            row_arr[$rc]=${csv_line[0]};
            #echo "This is row array"
            echo ${row_arr[$rc]}
            ((rc++))
        done < $loc${j}$txt

        row_arr_size="$(echo ${#row_arr[@]})"

        for ((i = 0; i < ${#row_arr[@]}; ++i));
        do

            if [ $(echo "${row_arr[$i]} >= $sub_val" | bc -l) -eq 1 ]
            then
                    echo ${row_arr[$i]} ">=" $sub_val
                    p='p'
                    pos=$i
                    echo "Index is="$pos

                    got_row=$pos
                    got_value="$(echo `sed -n $pos$p $loc${j}$txt`)"

                    echo "File="$loc${j}
                    echo "Row No="$got_row
                    echo "Value="$got_value
                    echo "Counter="$counter2
                    echo "##################################################################"

                    break

            fi
        done

                counter2=$[$counter2+1]
                if [ $counter2 -eq $fileList_size ]
                then
                    echo $counter2
                    exit 1
                fi
        row_no=$[$row_no+1]
        counter=$[$counter+1]
done

我收到此错误:

[: -eq: unary operator expected

如果我用>=替换-ge,那么我会收到此错误:

integer expression expected

1 个答案:

答案 0 :(得分:0)

以下命令给出了相同的错误

[  -eq 1 ]

如果bc输出为空,则会发生这种情况,如果出现错误,则会发生

一个简单的解决方法是处理空输出,如

[[ $(bc -l <<<"${row_arr[$i]} >= $sub_val") != 1 ]]
  • 如果第一个扩展为空,第一个参数为空字符串
  • ,则双括号的解析方式不同
  • !=是字符串比较,处理空字符串而-eq需要整数,因为bc输出可以是0 1