庆典:读取线文件到一个数组 [英] bash: Read lines in file into an array

查看:89
本文介绍了庆典:读取线文件到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读包含行的文件,到bash的数组。

I am trying to read a file containing lines, into a bash array.

我已经试过以下至今:

a=( $( cat /path/to/filename ) )

ATTEMPT2

index=0
while read line ; do
    MYARRAY[$index]="$line"
    index=$(($index+1))
done < /path/to/filename

两者的尝试失败,因为它们只返回包含该文件的第一行一个元件阵列。我在做什么错了?

Both attempt fail, in that they only return a one element array containing the first line of the file. What am I doing wrong?

我运行bash 4.1.5

推荐答案

根据从<评论最新修订版href=\"http://stackoverflow.com/questions/11393817/bash-read-lines-in-file-into-an-array/11393884?noredirect=1#comment56571512_11393884\">BinaryZebra's评论
这里测试。加入命令的eval 的允许前pression要保持在present执行环境而前pressions之前只举行了中的eval的持续时间。

Latest revision based on comment from BinaryZebra's comment and tested here. The addition of command eval allows for the expression to be kept in the present execution environment while the expressions before are only held for the duration of the eval.

使用$ IFS没有空格\\制表符,换行符刚刚/ CR

Use $IFS that has no spaces\tabs, just newlines/CR

$ IFS=$'\r\n' GLOBIGNORE='*' command eval  'XYZ=($(cat /etc/passwd))'
$ echo "${XYZ[5]}"
sync:x:5:0:sync:/sbin:/bin/sync

另外请注意,你可能会设置阵列得很好,但读错了 - 一定要同时使用双引号和括号 {} 在上面的例子中

编辑:

请注意有关我在有关可能扩大水珠评论答案的警告,特别是<一个href=\"http://stackoverflow.com/questions/11393817/bash-read-lines-in-file-into-an-array/11393884?noredirect=1#comment35615660_11393884\">gniourf-gniourf's评论关于我之前尝试解决

Please note the many warnings about my answer in comments about possible glob expansion, specifically gniourf-gniourf's comments about my prior attempts to work around

考虑到所有这些警告我还在这里离开这个答案(是的,bash的4已经流传了多年,但我记得,有些淅淅沥沥只有2/3岁有pre-4作为默认的shell )

With all those warnings in mind I'm still leaving this answer here (yes, bash 4 has been out for many years but I recall that some macs only 2/3 years old have pre-4 as default shell)

其他注意事项:

还可以按照崔斯特的建议之下,更换一个分叉子shell +猫

Can also follow drizzt's suggestion below and replace a forked subshell+cat with

$(</etc/passwd)

另一种选择我有时用刚刚设置IFS为XIFS,然后后恢复。另请参见 Sorpigal的回答

这篇关于庆典:读取线文件到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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