巴什从文件中读取到一个关联数组 [英] Bash reading from a file to an associative array

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

问题描述

我想写使用关联数组在bash脚本。
我有一个名为数据

  A,B,C,D,E,F
G,H,I,J,K,L

下面的脚本:

  oldIFS = $ {} IFS
IFS =,声明-A ASSOC
而读-a阵列

  ASSOC [$ {数组[0]}] =$ {数组[@]
DONE在$键{!assoc命令[@]}

  回声$ {}键---> $ {assoc命令[$ {键}]}
DONEIFS = $ {} oldIFS

给我

  A ---> A B C D E F摹---> G H I J K L

我需要我的输出是:

  A B --->维库电子G H&--- GT; I J K L


解决方案

  oldIFS = $ {} IFS
IFS =,声明-A ASSOC
而阅读-r -a阵列

  ASSOC [$ {数组[0]} $ {数组[1]}] =$ {数组[@]:2}
完成<数据在关键的$ {!assoc命令[@]}

  回声$ {}键---> $ {assoc命令[$ {键}]}
DONEIFS = $ {} oldIFS

数据:

  A,B,C,D,E,F
G,H,I,J,K,L

输出:

  A B --->维库电子
G H&--- GT; I J K L

子串扩展 这里 $ {数组[@]:2} 来获得所需子作为副教授值阵列。还增加了 -r 来prevent反斜杠充当转义字符。

根据@ gniourf_gniourf的建议改进:

 声明-A ASSOC
而IFS =读-r -a阵列

    (($ {#数组[@]}> = 2))||继续
    ASSOC [$ {数组[@]:0:2}] =$ {数组[@]:2}
完成<数据在关键的$ {!assoc命令[@]}

    回声$ {}键---> $ {assoc命令[$ {键}]}
DONE

I'm trying to write a script in bash using an associative array. I have a file called data:

a,b,c,d,e,f
g,h,i,j,k,l

The following script:

oldIFS=${IFS}
IFS=","

declare -A assoc
while read -a array
do 
  assoc["${array[0]}"]="${array[@]"
done

for key in ${!assoc[@]}
do
  echo "${key} ---> ${assoc[${key}]}"
done 

IFS=${oldIFS}

gives me

a ---> a b c d e f

g ---> g h i j k l

I need my output to be:

a b ---> c d e f

g h ---> i j k l

解决方案

oldIFS=${IFS}
IFS=","

declare -A assoc
while read -r -a array
do 
  assoc["${array[0]} ${array[1]}"]="${array[@]:2}"
done < data

for key in "${!assoc[@]}"
do
  echo "${key} ---> ${assoc[${key}]}"
done

IFS=${oldIFS}

data:

a,b,c,d,e,f
g,h,i,j,k,l

Output:

a b ---> c d e f
g h ---> i j k l

Uses Substring Expansion here ${array[@]:2} to get substring needed as the value of the assoc array. Also added -r to read to prevent backslash to act as an escape character.

Improved based on @gniourf_gniourf's suggestions:

declare -A assoc
while IFS=, read -r -a array
do 
    ((${#array[@]} >= 2)) || continue
    assoc["${array[@]:0:2}"]="${array[@]:2}"
done < data

for key in "${!assoc[@]}"
do
    echo "${key} ---> ${assoc[${key}]}"
done

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

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