Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

bash - Read tab-separated file line into array

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.

Typical bash "read file by line" example;

while read line
do
echo $line;
done < "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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're very close:

while IFS=$'' read -r -a myArray
do
 echo "${myArray[0]}"
 echo "${myArray[1]}"
 echo "${myArray[2]}"
done < myfile

(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=$'' 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.?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...