使用mapfile读取值时bash数组无法正确处理

使用mapfile读取值时bash数组无法正确处理

这个让我很困惑。

这里有 2 个加载 bash 数组的版本,一个有效,另一个无效。

如果我在脚本中显式初始化数组,它就可以正常工作:

zz=( 1 26 32 54 71 13 30 43 52 73 7 23 42 57 61 15 27 35 56 66 5 20 36 51 68 )

#print in reverse
for i in {24..0}
do
        echo "zz[$i] is ${zz[$i]}"
done

输出如预期:

zz[24] is 68
zz[23] is 51
zz[22] is 36
zz[21] is 20
zz[20] is 5
zz[19] is 66
zz[18] is 56
zz[17] is 35
zz[16] is 27
zz[15] is 15
zz[14] is 61
zz[13] is 57
zz[12] is 42
zz[11] is 23
zz[10] is 7
zz[9] is 73
zz[8] is 52
zz[7] is 43
zz[6] is 30
zz[5] is 13
zz[4] is 71
zz[3] is 54
zz[2] is 32
zz[1] is 26
zz[0] is 1

该版本无法正常工作(目前):

# cat your_data
1 26 32 54 71 13 30 43 52 73 7 23 42 57 61 15 27 35 56 66 5 20 36 51 68
mapfile -t zz < your_data

#print in reverse
for i in {24..0}
do
        echo "zz[$i] is ${zz[$i]}"
done


Output:
zz[24] is
zz[23] is
zz[22] is
zz[21] is
zz[20] is
zz[19] is
zz[18] is
zz[17] is
zz[16] is
zz[15] is
zz[14] is
zz[13] is
zz[12] is
zz[11] is
zz[10] is
zz[9] is
zz[8] is
zz[7] is
zz[6] is
zz[5] is
zz[4] is
zz[3] is
zz[2] is
zz[1] is
zz[0] is 1 26 32 54 71 13 30 43 52 73 7 23 42 57 61 15 27 35 56 66 5 20 36 51 68

因此,当通过mapfile读取数据时,所有数据都会被填充到zz[0]中。即使我明确将 IFS 设置为仅空格(“”)。我很确定这在某些时候是有效的,所以也许这在我的环境中是有效的。我很困惑...

谢谢,斯纳克斯达德

答案1

mapfile命令按行读取文件,即期望它们以\n.由于数据以空格分隔,因此文件中的这一(唯一)行被视为单个标记,因此分配给第一个数组位置。尝试更改您的输入文件,如下所示

1
26
32

...

68

应该是有窍门的。

答案2

如果所有数据都位于文件中以空格分隔的一行中,请执行以下操作:

read -r -a arrayname < filename

-a 是这里的关键:从文件中读取一行,根据 $IFS 分割它,并将字段存储在数组中。

正如已经指出的,mapfile 将文件分割为线不由

相关内容