[英]Assigning values to an array in Bash shell script
我有一個純文本文件,其中包含曲目標題和藝術家,並用破折號分隔。 我想將所有標題放入一個數組( TRK_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"
因此,當散列位於它們所在的位置時,輸出為:
獻給我愛的人-媽媽和爸爸
獻給我所愛的人
媽媽和爸爸
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"
您的腳本可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.