【问题标题】:How to create a dictionary from a text file in bash?如何从 bash 中的文本文件创建字典?
【发布时间】:2020-03-14 15:00:54
【问题描述】:

我想从一个看起来像这样的文本文件在 bash 中创建一个字典:

H96400275|A
H96400276|B
H96400265|C
H96400286|D

基本上我想从这个文件file.txt中得到这样的字典:

KEYS        VALUES
H96400275 = A
H96400276 = B
H96400265 = C
H96400286 = D

我创建了以下脚本:

#!/bin/bash
declare -a dictionary

while read line; do 

  key=$(echo $line | cut -d "|" -f1)
  data=$(echo $line | cut -d "|" -f2)
  dictionary[$key]="$data"
done < file.txt


echo ${dictionary[H96400275]}

但是,这不会打印A,而是打印D。你能帮忙吗?

【问题讨论】:

标签: bash shell dictionary


【解决方案1】:

你要做的就是这样命名的关联数组。要声明它,您需要使用命令:

declare -A dictionary

【讨论】:

    【解决方案2】:

    关联数组(字典在您的术语中)使用 -A 声明,而不是 -a。对于索引(用-a 声明的)数组元素的引用,bash 对下标(在这种情况下为$keyH96400275)执行算术扩展;所以你基本上一遍又一遍地覆盖dictionary[0],然后询问它的价值;因此D 被打印出来。

    为了使这个脚本更有效,您可以将read 与自定义IFS 结合使用,以避免cuts。例如:

    declare -A dict
    
    while IFS='|' read -r key value; do
        dict[$key]=$value
    done < file
    
    echo "${dict[H96400275]}"
    

    Bash Reference Manual § 6.7 Arrays

    【讨论】:

    • 这是另一种避免与调用 cut 相关的子shell的好方法。
    【解决方案3】:

    唯一的问题是你必须使用 -A 而不是 -a

          -a     Each name is an indexed array variable (see Arrays above).
          -A     Each name is an **associative** array variable (see Arrays above).
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      相关资源
      最近更新 更多