小编Mow*_*gli的帖子

在 shell 脚本中使用空行空间分割文件并存储在数组中

我试图用空行作为分隔符分割 myfile.txt 并将每个值存储在数组中。

fruit=mango, lime, orange,grape

car=nissan,
ford,
toyota,
honda

country=russia, england, ireland,
usa,
mexico,australia

colors=green, orange, purple, white,
yellow
Run Code Online (Sandbox Code Playgroud)

我写了以下脚本

while IFS='\n' read -r line || [[ -n "$line" ]]; do
    if [[ $line != "" ]]; then
        arr+=("$line")
        echo "File Content : $line"
    fi
done < myfile.txt
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是对于国家来说它是这样的

File Content : country=russia, england, ireland
File Content : usa,
File Content : mexico,australia
Run Code Online (Sandbox Code Playgroud)

我希望将其打印为

File Content : country=russia, england, ireland, usa,mexico,australia
Run Code Online (Sandbox Code Playgroud)

你能帮我调整一下我的剧本吗?

提前致谢

shell

5
推荐指数
1
解决办法
1011
查看次数

使用python编写json文件

我正在尝试使用python脚本读取和编写json文件(我在shell脚本中嵌入了这个python块)

test.json

{
  "environments": ["dev", "qa", "load", "prod"],
  "region": ["asia", "europe", "americas", "asia-pacific"],
  "product": ["mobile", "internet", "kiosk", "branch"],
  "ID": ["mobile:111", "internet:222", "kiosk:333", "branch:444"]
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试添加区域(英国),在此之前我想检查并添加它是否在列表中不可用.下面是我的python代码,我可以更新值

reg_val="uk"

a_dict = {}
try:
    with open('test.json') as data_file:
        data = json.load(data_file)
        temp_list = []
        for dicObj in data["region"]:
            temp_list.append(dicObj)
        temp_list.append(reg_val)
        data["region"] = temp_list
        a_dict["region"] = data["region"]
        with open('test.json','w') as f:
            f.write(json.dumps(a_dict, indent=4, sort_keys=True, encoding="utf-8"))
except IOError as io:
    print "ERROR: ", io
Run Code Online (Sandbox Code Playgroud)

我能够更新json文件,但它删除了其他列表.我看到的输出是

{
    "region": [
        "asia", 
        "europe", 
        "americas", 
        "asia-pacific", 
        "uk"
    ]
}
Run Code Online (Sandbox Code Playgroud)

python json

1
推荐指数
1
解决办法
738
查看次数

标签 统计

json ×1

python ×1

shell ×1