简体   繁体   中英

Traversing floating array for comparison in bash

I am extracting float column from csv file and storing in row_arr array. Next am comparing a stored value in sub_val against the array elements. I want to store index of the matching element in a variable. I have the following code and errors.

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

and i get this error:

[: -eq: unary operator expected

if i replace >= with -ge then i get this error:

integer expression expected

Following command gives the same error

[  -eq 1 ]

it can occur if bc output is empty, which occurs in case of error

a simple workaround is to handle the empty output like

[[ $(bc -l <<<"${row_arr[$i]} >= $sub_val") != 1 ]]
  • The double bracket is parsed differently if the first expansion is empty, first argument is empty string
  • != is a string comparison, handles the empty string whereas -eq requires an integer, because bc output can be 0 1 or

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM