将文件中的行读入Bash数组 [英] Read lines from a file into a Bash array

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

问题描述

我正在尝试将包含行的文件读取到Bash数组中.

到目前为止,我已经尝试了以下方法:

Attempt1

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

Attempt2

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

两次尝试都只返回一个包含文件第一行的元素数组.我在做什么错了?

我正在运行bash 4.1.5

解决方案

基于在此处进行了测试.添加command eval可以使表达式保留在当前执行环境中,而之前的表达式仅在eval持续时间内保留.

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

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

还请注意,您可能将数组设置得很好,但读错了-请确保如上例所示同时使用双引号""和大括号{}


请在有关可能的全局扩展的注释中注意有关我的答案的许多警告,特别是 Sorpigal的答案,它无需为此烦恼

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

I have tried the following so far:

Attempt1

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

Attempt2

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

Both attempts only return a one element array containing the first line of the file. What am I doing wrong?

I am running bash 4.1.5

解决方案

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.

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

Also note that you may be setting the array just fine but reading it wrong - be sure to use both double-quotes "" and braces {} as in the example above


Edit:

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

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)

Other notes:

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

$(</etc/passwd)

The other option I sometimes use is just set IFS into XIFS, then restore after. See also Sorpigal's answer which does not need to bother with this

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

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