bash4 将文件读入关联数组 [英] bash4 read file into associative array

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

问题描述

我可以使用单个语句将文件读入常规数组:

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.

我可以控制文件的创建,因此希望尽可能简单地不使用循环.

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.

那么是否有可能使用诸如 untilfrom 之类的东西将这样的文件读入 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

或者使用 -g 如果 BASH_VERSION >= 4.2.

如果你的行确实有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屋!

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