使用以下代码,我试图构建一个开始/结束对的输出数组,以便在预生成的输入文件中使用脚本中的其他位置。但是我遇到了一个问题,而不是将最终数据连接到起始数据上,它似乎覆盖了已有的数据?
#!/bin/bash
echo "Init arrays"
far=()
near=()
echo "Start while"
while read -u2 line; do
echo " $line"
if [[ "$line" == "Far Start"* ]]; then
far+=(${line##* })
echo ${far[-1]}
elif [[ "$line" == "Far End"* ]]; then
far[-1]+="-${line##* }"
echo ${far[-1]}
elif [[ "$line" == "Near Start"* ]]; then
near+=(${line##* })
echo ${near[-1]}
elif [[ "$line" == "Near End"* ]]; then
near[-1]+="-${line##* }"
echo ${near[-1]}
fi
done 2<screenlog.0
echo
echo " Far array"
for each in "${far[@]}"
do
echo "$each"
done
echo " Near array"
for each in "${near[@]}"
do
echo "$each"
done
输入文件(screenlog.0):
User Input: 955
Stepping Pass 1/6
Far Start 213994
Far End 216994
Near Start 221795
Near End 224795
Stepping Pass 2/6
Far Start 229596
Far End 232596
Near Start 237397
Near End 240397
Stepping Pass 3/6
Far Start 245198
Far End 248198
Near Start 252999
Near End 255999
Stepping Pass 4/6
Far Start 260800
Far End 263800
Near Start 268601
Near End 271601
Stepping Pass 5/6
Far Start 276402
Far End 279402
Near Start 284203
Near End 287203
Stepping Pass 6/6
Far Start 292004
Far End 295004
Near Start 299805
Near End 302805
Finished!
输出错误:
Init arrays
Start while
User Input: 955
Stepping Pass 1/6
Far Start 213994
213994
Far End 216994
-216994
Near Start 221795
221795
Near End 224795
-224795
Stepping Pass 2/6
Far Start 229596
229596
Far End 232596
-232596
Near Start 237397
237397
Near End 240397
-240397
Stepping Pass 3/6
Far Start 245198
245198
Far End 248198
-248198
Near Start 252999
252999
Near End 255999
-255999
Stepping Pass 4/6
Far Start 260800
260800
Far End 263800
-263800
Near Start 268601
268601
Near End 271601
-271601
Stepping Pass 5/6
Far Start 276402
276402
Far End 279402
-279402
Near Start 284203
284203
Near End 287203
-287203
Stepping Pass 6/6
Far Start 292004
292004
Far End 295004
-295004
Near Start 299805
299805
Near End 302805
-302805
Finished!
Far array
-216994
-232596
-248198
-263800
-279402
-295004
Near array
-224795
-240397
-255999
-271601
-287203
-302805
关于预期的结果,far数组应该看起来像下面这样,(IE的起始编号后跟分隔符后跟结束编号)。 near数组应该是相同的,只需从near数据中提取。
[0] 213994-216994
[1] 229596-232596
[2] 245198-248198
[3] 260800-263800
[4] 276402-279402
[5] 292004-295004
我尝试使用相同结果的array[-1]="${array[-1]}-${line##* }"
语法,以及更改分隔符并使用${array[@]:-1}
引用数组的最后一个元素。
编辑:根据William的建议,我尝试用far[-1]
替换far[$((${#far[@]}-1))]
语法的所有实例,这导致与far[-1]
语法相同的错误输出。
答案 0 :(得分:2)
而不是for each .. echo ..
,请使用declare -p far near
查看是否有不可打印的字符
可能会打印类似
的内容declare -a far=([0]=$'213994\r-216994\r' [1]=$'229596\r-232596\r' [2]=$'245198\r-248198\r' [3]=$'260800\r-263800\r' [4]=$'276402\r-279402\r' [5]=$'292004\r-295004\r')
declare -a near=([0]=$'221795\r-224795\r' [1]=$'237397\r-240397\r' [2]=$'252999\r-255999\r' [3]=$'268601\r-271601\r' [4]=$'284203\r-287203\r' [5]=$'299805\r-302805\r')
如果是这样的情况&#39; \ r&#39;字符可以删除,添加
line=${line%$'\r'}
刚读完之后(更准确地说是do
之后,否则循环永远不会结束)