Arrays 在bashshell脚本中为数组赋值

Arrays 在bashshell脚本中为数组赋值,arrays,bash,shell,Arrays,Bash,Shell,我有一个纯文本文件,其中包含曲目标题和艺术家,以破折号分隔。 我想将所有标题放入一个数组(TRK\u TITLE[])。 同时创建艺术家阵列(ARTIST[])。 下面是我正在使用的代码: CTR=0 # Read in the track title file while read line do # Add to the counter CTR=$((CTR + 1)) # Get the track number TRK_NUM[$CTR]=$CTR # VARI

我有一个纯文本文件,其中包含曲目标题和艺术家,以破折号分隔。 我想将所有标题放入一个数组(
TRK\u TITLE[]
)。 同时创建艺术家阵列(
ARTIST[]
)。 下面是我正在使用的代码:

CTR=0
# Read in the track title file
while read line

do 

# Add to the counter
    CTR=$((CTR + 1))

# Get the track number
    TRK_NUM[$CTR]=$CTR

# VARIOUS is set by command line parameter
if [ $VARIOUS = "FALSE" ]
then
# -- THIS BIT WORKS! ------------------------------
TRK_TITLE[$CTR]=${line}
# ARTISTS determined by grandparent directory name.
ARTIST[$CTR]="$ARTISTS"

# THE BIT THAT DOESN'T WORK AS IT APPEARS --------- 
else
# VARIOUS has been set to TRUE
# Get the track title
# 1st, Make sure I'm dealing with something sensible
echo "$line"
# Get the length of the line,
# just for information
total_len=${#line}
# Find the position of the "-"
dash_pos=`expr index "$line" -`

# These lines prove that the syntax works
echo "${line:0:$dash_pos - 2}"

echo "${line:$dash_pos + 1}"

echo $total_len "--" $dash_pos 
# Now add to arrays
TRK_TITLE[$CTR]="${line:0:$dash_pos -2}"
#TRK_TITLE="${line:0:$dash_pos -2}"

ARTIST[$CTR]="${line:$dash_pos + 1}"
#ARTIST="${line:$dash_pos + 1}"

#Now to see the output
echo $TRK_TITLE[$CTR] "is Track"
#echo "$TRK_TITLE is Track"

echo $ARTIST[$CTR] "is Artist"
#echo "$ARTIST is Artist"

fi

# keep going until the end
# Variable name used for input file
done < "$FYL_2_USE"
CTR=0
#读入曲目标题文件
读行时
做
#添加到柜台
中心利率=$((中心利率+1))
#获取曲目编号
TRK_NUM[$CTR]=$CTR
#各种参数由命令行参数设置
如果[$variable=“FALSE”]
然后
#--这个钻头管用------------------------------
TRK_标题[$CTR]=${line}
#艺术家由祖父母目录名决定。
艺术家[$CTR]=“艺术家”
#看起来不起作用的钻头------
其他的
#已设置为“真”
#获得曲目标题
#首先,确保我在处理一些明智的事情
回音“$line”
#获取线的长度,
#仅供参考
总长度=${line}
#找到“-”的位置
破折号位置=`expr索引“$line”-`
#这些行证明了语法是有效的
回显“${line:0:$dash_pos-2}”
回显“${line:$dash_pos+1}”
echo$total_len“-“$dash_pos
#现在添加到数组
TRK_TITLE[$CTR]=“${line:0:$dash_pos-2}”
#TRK_TITLE=“${line:0:$dash_pos-2}”
艺术家[$CTR]=“${line:$dash_pos+1}”
#艺人=“${line:$dash_pos+1}”
#现在查看输出
echo$TRK_标题[$CTR]“是曲目”
#echo“$TRK_标题是曲目”
echo$ARTIST[$CTR]“是艺术家”
#echo“$艺术家就是艺术家”
fi
#一直走到最后
#用于输入文件的变量名
完成<“$FYL\u 2\u使用”
当散列位于它们所在的位置时,输出为:

献给我爱的人——妈妈和爸爸

献给我所爱的人

妈妈和爸爸

53-29

[19] 是轨道

[19] 是艺术家吗

如果在变量和echo上交换哈希值 语句,因此输出为:

献给我爱的人——妈妈和爸爸

献给我所爱的人

妈妈和爸爸

53-29

献给我所爱的人是轨道

妈妈和爸爸是艺术家

Shell是Gnu Bash V4.1.0(2)

如果更换:

echo $TRK_TITLE[$CTR] "is Track"
echo $ARTIST[$CTR] "is Artist"
与:


你的脚本会很好用。

谢谢你发现了我的明显错误,托马斯,我怎么能看不到呢?
echo ${TRK_TITLE[$CTR]} "is Track"
echo ${ARTIST[$CTR]} "is Artist"