将制表符分隔的文件行读入数组 [英] Read tab-separated file line into array

查看:53
本文介绍了将制表符分隔的文件行读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件逐行读入脚本.文件中的每一行都是由制表符分隔的多个值,我想将每一行读入一个数组.

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.?)

这篇关于将制表符分隔的文件行读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆