问题描述
我想逐行将文件读入脚本.文件中的每一行都是由一个制表符分隔的多个值,我想将每一行读入一个数组.
I would like to read a file into a script, line by line. Each line in the file is multiple values separated by a tab, I'd like to read each line into an array.
典型的bash按行读取文件"示例;
Typical bash "read file by line" example;
while read line
do
echo $line;
done < "myfile"
对我而言,myfile看起来像这样(用制表符分隔的值);
For me though, myfile looks like this (tab separated values);
value1 value2 value3
value4 value5 value6
在循环的每次迭代中,我希望每一行都进入一个数组,以便可以
On each iteration of the loop, I'd like each line to go into an array so I can
while read line into myArray
do
echo myArray[0]
echo myArray[1]
echo myArray[2]
done < "myfile"
这将在第一次循环迭代中打印以下内容;
This would print the following on the first loop iteration;
value1
value2
value3
然后在第二次迭代中将打印
Then on the second iteration it would print
value4
value5
value6
这可能吗?我能看到的唯一方法是编写一个小的函数来手动分解值,这在bash中是否为此提供了内置支持?
Is this possible? The only way I can see is to write a small function to break out the values manually, is there built in support in bash for this?
推荐答案
您非常亲密:
while IFS=$'\t' read -r -a myArray
do
echo "${myArray[0]}"
echo "${myArray[1]}"
echo "${myArray[2]}"
done < myfile
(-r
告诉read
在输入数据中\
并不特殊; -a myArray
告诉它将输入行拆分为单词并将结果存储在myArray
中; IFS=$'\t'
告诉它仅使用制表符来分隔单词,而不是常规的Bash默认值(也允许空格来分隔单词),请注意,这种方法会将一个个或多个制表符视为分隔符,因此,如果任何字段为空白,则后面的字段将被移动"到数组中的前面位置.可以吗?)
(The -r
tells read
that \
isn't special in the input data; the -a myArray
tells it to split the input-line into words and store the results in myArray
; and the IFS=$'\t'
tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)
这篇关于将制表符分隔的文件行读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!