将值分配给特定索引处的数组

将值分配给特定索引处的数组

您好,我正在尝试编写一个脚本来更新从文件中读取的行,到目前为止,除了最后提到的以下行之外,一切都工作正常

这是我的脚本:

#!/bin/bash     

#INITIALIZE PATHS
DB_PATH=${1}      
DATA_PATH="$DB_PATH/data/"
METADATA_PATH="$DB_PATH/metadata"   

#LOAD THE META DB FILE AND READ DATABASE NAME IN DB_NAME 
#READ ALSO COLUMNS IN AN ARRAY CALLED TABLE_NAMES                      
METADATA_LOAD=$(<"$METADATA_PATH/DB")
IFS=$'+'
read -a NAMES <<< "$METADATA_LOAD"



#PROMPET FOR TABLE TO UPDATE
echo ""
echo ""
echo ""
echo "You Currently Working with Database ${NAMES[0]}" 
echo ""
echo "You Have The Following Tables to Choose From :"
IFS=' '
for token in ${NAMES[@]:1}
do
echo "  $token"
done
echo ""
echo ""
echo ""
echo "Please Write The Name Of The Table You Want To Update :"
read CURRENT_TABLE


#Form META DATA TABLE FILE PATH
TABLE_DATA_PATH="$DB_PATH/data/$CURRENT_TABLE"
TABLE_METADATA_PATH="$DB_PATH/metadata/$CURRENT_TABLE"


#PROMPET WHICH COLUMN IS NEEDED TO CHECK FOR EQUALITY
echo ""
echo ""
echo ""
echo "The Table You Selected Have The Following Columns"
i=0 
TABLE_METADATA=$(<"$TABLE_METADATA_PATH")
IFS='+'
read -a CURRENT_TABLE_META <<< "$TABLE_METADATA"
IFS=' '
for token in ${CURRENT_TABLE_META[@]:1}
do
i=$(($i+1))
echo $i $token
done
echo "Please Enter The Number Column to Check For Equality"
read TEST_COLUMN_NUM
echo ""
echo ""
echo "Please Enter The Column Value to Check For Equality"
read TEST_COLUMN_VAL

echo "Please Enter The Column Number to Modify"
read MODIFY_COLUMN_NUM

echo "Please Enter The New Column Value"
read MODIFY_COLUMN_VAL

#Form DATA TABLE FILE PATH
TABLE_DATA=$(<"$TABLE_DATA_PATH") 


IFS=' '
read -a ROWS_ARRAY <<< "$TABLE_DATA"  




for CURRENT_ROW_INDEX in ${!ROWS_ARRAY[@]}
do

  IFS=':'
  read -a COLUMNS_ARRAY <<< "${ROWS_ARRAY[CURRENT_ROW_INDEX]}"

   for CURRENT_COL_INDEX in ${!COLUMNS_ARRAY[@]} 
   do

       if [[ ${COLUMNS_ARRAY[$CURRENT_COL_INDEX]} == $TEST_COLUMN_VAL  &&  $CURRENT_COL_INDEX -eq $(($TEST_COLUMN_NUM-1)) ]]
       then

           IFS=' '
           COLUMNS_ARRAY[$MODIFY_COLUMN_NUM] = "ABC"



       fi   

   done
done

我还没有完成脚本,但我在该行出现错误:

 COLUMNS_ARRAY[$MODIFY_COLUMN_NUM] = "ABC"

它给了我错误

./更新:第 91 行:COLUMNS_ARRAY[3]:找不到命令

我想分配给给定索引处的数组替换旧值,请帮助我了解错误原因以及如何解决它

答案1

与 shell 中的常规变量分配相同,不要在=.

给定,这是对中i=123索引的赋值:123array

array[$i]="abc"

这会尝试运行一个名为的命令array[123](或者如果找到与 glob 模式匹配的文件名,则任何结果):

array[$i] = "abc"

另外,每次使用${array[@]}, 时,无论是否带有!or :n:m,您都可能需要在其周围加上引号。如果没有引号,数组值会受到分词的影响,而有引号则不会。

你有,例如for token in ${NAMES[@]:1}for .. in ${!ROWS_ARRAY[@]}

相关内容