如何在bash中使用'readarray'将文件中的行读取到2D数组中 [英] How to use 'readarray' in bash to read lines from a file into a 2D array
问题描述
假设我有一个文本文件'demo.txt',其中有一个这样的表:
Let's say I have a text file 'demo.txt' who has a table in it like this:
1 2 3
4 5 6
7 8 9
现在,我想使用bash中的"readarray"命令分别读取每一行,所以我写:
Now, I want to read each line separately using the 'readarray' command in bash, so I write:
readarray myarray < demo.txt
问题是它不起作用.如果我尝试使用以下命令打印"myarray":
The problem is that it doesn't work. If I try to print 'myarray' with:
echo $myarray
我得到:
1 2 3
另外,如果我写:
echo ${myarray[1]}
我得到:
4 5 6
代替:
2
如我所料.这是为什么?如何分别访问每条线并在该行中获得对每个成员的访问权?
as I expected. Why is that? How can accesses each line separately and in that line get access to each member?
推荐答案
这是预期的行为. readarray
将创建一个数组,其中数组的每个元素都是输入中的一行.
This is the expected behavior. readarray
will create an array where each element of the array is a line in the input.
如果要查看整个阵列,请使用
If you want to see the whole array you need to use
echo "${myarray[@]}"
as echo "$myarray
将仅输出myarray[0]
,而${myarray[1]}
是数据的第二行.
as echo "$myarray
will only output myarray[0]
, and ${myarray[1]}
is the second line of the data.
您要寻找的是二维数组.例如,请参见此.
What you are looking for is a two-dimensional array. See for instance this.
如果要使用包含第一行内容的数组,则可以这样:
If you want an array with the content of the first line, you can do like this:
$ read -a arr < demo.txt
$ echo ${arr[0]}
1
$ echo ${arr[1]}
2
$ echo ${arr[2]}
3
这篇关于如何在bash中使用'readarray'将文件中的行读取到2D数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!