bash4将文件读入关联数组 [英] bash4 read file into associative array
问题描述
我能够用一条语句将文件读入常规数组:
I am able to read file into a regular array with a single statement:
local -a ary
readarray -t ary < $fileName
没有发生将文件读入assoc的情况.数组.
Not happening is reading a file into assoc. array.
我可以控制文件的创建,因此希望尽可能简单地执行w/o循环.
I have control over file creation and so would like to do as simply as possible w/o loops if possible at all.
因此,可以按照以下方式读取文件内容:
So file content can be following to be read in as:
keyname=valueInfo
但是如果减少了代码,尤其是上面的单行代码,我愿意用另一个字符串替换=.
But I am willing to replace = with another string if cuts down on code, especially in a single line code as above.
那么有可能使用until
或from
之类的东西将这样的文件读入assoc数组中-即读入assoc数组中直到碰到一个单词,或者我必须做一部分循环?
So would it be possible to read such a file into an assoc array using something like an until
or from
- i.e. read into an assoc array until it hits a word, or would I have to do this as part of loop?
这将使我可以在同一文件中保留许多相似的值,但可以读取到单独的数组中.
This will allow me to keep a lot of similar values in same file, but read into separate arrays.
我也看过mapfile
,但是和readarray
一样.
I looked at mapfile
as well, but does same as readarray
.
我正在创建一个选项列表-从-中进行选择,如下所示:
I am creating an options list - to select from - as below:
local -a arr=("${!1}")
select option in ${arr[*]}; do
echo ${option}
break
done
工作正常-但是显示的列表未排序.我想尽可能对它进行排序.
Works fine - however the list shown is not sorted. I would like to have it sorted if possible at all.
希望可以将所有3个问题放到1个中,因为这些问题是相似的-全部在数组上.
Hope it is ok to put all 3 questions into 1 as the questions are similar - all on arrays.
谢谢.
推荐答案
第一件事,关联数组用-A
而不是-a
声明:
First thing, associative arrays are declared with -A
not -a
:
local -A ary
如果要在全局范围内声明变量,请在函数外部使用declare
:
And if you want to declare a variable on global scope, use declare
outside of a function:
declare -A ary
或者如果BASH_VERSION >= 4.2
,则使用-g
.
如果您的行中确实包含keyname=valueInfo
和readarray
,则可以这样处理:
If your lines do have keyname=valueInfo
, with readarray
, you can process it like this:
readarray -t lines < "$fileName"
for line in "${lines[@]}"; do
key=${line%%=*}
value=${line#*=}
ary[$key]=$value ## Or simply ary[${line%%=*}]=${line#*=}
done
使用while read
循环也可以是一种选择:
Using a while read
loop can also be an option:
while IFS= read -r line; do
ary[${line%%=*}]=${line#*=}
done < "$fileName"
或
while IFS== read -r key value; do
ary[$key]=$value
done < "$fileName"
这篇关于bash4将文件读入关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!