如何使用Shell脚本创建字典 [英] How to create dictionary using shell script

查看:238
本文介绍了如何使用Shell脚本创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

1|A|B
2|C|D

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

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.

推荐答案

根据while循环的想法,这里是解决方法:

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"

这篇关于如何使用Shell脚本创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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