使用bash以类似字典的格式进行迭代

编程入门 行业动态 更新时间:2024-10-27 02:21:16
本文介绍了使用bash以类似字典的格式进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在输入文件中有一个类似python的字典:

I have a python like dictionary in an input file:

$ cat test.txt db={1:['a','b','c','d'], 2:['aa','bb','cc','dd']}

字典中的每个列表只有4个索引,且该索引不小于或大于.我需要这样的结果:

Each list in dictionary only has 4 indexes not less or more. I need a result like:

one1="a" two1="b" three1="c" four1="d" one2="aa" two2="bb" three2="cc" four2="dd"

如果我们在这里使用python,我知道这很简单,但是我应该在bash脚本中完成这项工作.是否可以?如何使用bash脚本完成这项工作?

I know this is simple if we use python here, but I should do the job in bash script. Is it possible? How can I do the job using bash script?

推荐答案

您只需要剥离所有不必要的字符并循环遍历它们即可得到结果

you just need to strip off all the unnecessary characters and loop through them to get your result

#!/bin/bash db="{1:['a','b','c','d'], 2:['aa','bb','cc','dd']}" count=1 for items in `echo $db|sed 's/{//;s/}//'` do echo one${count} = `echo $items|sed 's/^.*\[//;s/\].*$//'|cut -d ',' -f1` echo two${count} = `echo $items|sed 's/^.*\[//;s/\].*$//'|cut -d ',' -f2` echo three${count} = `echo $items|sed 's/^.*\[//;s/\].*$//'|cut -d ',' -f3` echo four${count} = `echo $items|sed 's/^.*\[//;s/\].*$//'|cut -d ',' -f4` echo '' count=`expr $count + 1` done

输出

one1 = 'a' two1 = 'b' three1 = 'c' four1 = 'd' one2 = 'aa' two2 = 'bb' three2 = 'cc' four2 = 'dd'

更多推荐

使用bash以类似字典的格式进行迭代

本文发布于:2023-10-29 07:42:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539114.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   类似   迭代   格式   bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!