bash 如何使用shell脚本创建字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23382726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:20:46  来源:igfitidea点击:

How to create dictionary using shell script

bashshell

提问by Sonal Maheshwari

I have a file status.txt which is in the following format:

我有一个文件 status.txt,其格式如下:

1|A|B
2|C|D

Now i have to read this file in shell script and create a dictionary like:

现在我必须在 shell 脚本中读取这个文件并创建一个字典,如:

dictionary['1'] = ['A', 'B']
dictionary['2'] = ['C', 'D']

I am able read the content of file using this:

我可以使用这个读取文件的内容:

while read line
    do
        key=$line | cut --d="|" -f1
        data1=$line | cut --d="|" -f2
        data2=$line | cut --d="|" -f3
    done < "status.txt"

Can anybody help me in creating the dictionary as mentioned above.

任何人都可以帮助我创建上述字典。

回答by BMW

According your idea with while loop, here is the fix:

根据你对 while 循环的想法,这里是修复:

#!/usr/bin/env bash

while IFS="|" read -r key data1 data2
do 
  echo "dictionary['${key}'] = ['${data1}', '${data2}']"
done <"status.txt"

回答by rojomoke

Change your assignment lines to be like this:

将您的分配行更改为如下所示:

key=$(echo $line | cut -d"|" -f1)

And then add the following line

然后添加以下行

printf "dictionary['%d'] = ['%s', '%s']\n" $key $data1 $data2

回答by Steven Penny

#!awk -f
BEGIN {
  FS = "|"
}
{
  printf "dictionary['%s'] = ['%s', '%s']\n", , , 
}

回答by ahmed sharief

According to the previous answers i could figure out a solution

根据以前的答案,我可以找到解决方案

#!/usr/bin/env bash

while IFS="|" read -r key data1 data2
do 
  echo "{'${key}' : {'${data1}', '${data2}'}},"
done <"status.txt"

So it will give the result something like as follows

所以它会给出如下结果

{'key1' : {'data1', 'data2'}, 'key2' : {'data1', 'data2'}}

Then you can use this result in any other language. Example: Python - Convert the above dictionary string to json by
1. json.dumps(result)to convert single quotes tto double quotes
2. json.loads(result)to convert string to json

然后您可以在任何其他语言中使用此结果。示例:Python - 将上述字典字符串转换为 json by
1. json.dumps(result)将单引号 t
2. json.loads(result)转换为双引号将字符串转换为 json