How to create dictionary using shell script

余生颓废 提交于 2021-01-29 16:21:43

问题


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

1|A|B
2|C|D

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

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.


回答1:


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

#!/usr/bin/env bash

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



回答2:


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



回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/23382726/how-to-create-dictionary-using-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!