击:阅读制表符分隔文件行到数组 [英] Bash: Read tab-separated file line into array

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

问题描述

我想文件读入一行的脚本,行。文件中的每一行由制表分隔多个值,我想读取每一行成一个阵列。

I would like to read a file into a script, line by line. Each line in the file is multiple values seperated 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 告诉 \\ 是不是在输入数据特别的, -a myarray的告诉它拆分输入线成词,并将结果保存在 myArray的;和 IFS = $'\\ t'告诉它仅使用标签来分割的话,不是也让空间分割经常猛砸默认词为好。注意,这种方法将治疗一种的以上的标签作为分隔符,所以如果任何字段为空,后场将是转移到数组前面的位置。这样可以吗? )

(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天全站免登陆