使用Sed查找和替换json字段 [英] Use Sed to find and replace json field

查看:827
本文介绍了使用Sed查找和替换json字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组json文件,其中最后一个键值对之后有逗号,需要替换.

I have set of json files where after last key value pair i have comma which needs to be replaced.

{
    "RepetitionTime": 0.72,
    "TaskName":"WM",
    "Manufacturer": "Siemens",
    "ManufacturerModelName": "Skyra",
    "MagneticFieldStrength": 3.0,
    "EchoTime":"0.033",
}

它应该像这样:

{
    "RepetitionTime": 0.72,
    "TaskName":"WM",
    "Manufacturer": "Siemens",
    "ManufacturerModelName": "Skyra",
    "MagneticFieldStrength": 3.0,
    "EchoTime": 0.033
}

我如何使用sed实现这一目标. 更改输出-0.033左右不应有任何".

How can i achive this using sed. Changed output - There should not be any "" around 0.033.

sed -i  \'7i'\\t'\"EchoTime\": \0.033\' sub-285345_task-WM_acq-RL_bold.json

没有帮助我.我尝试了其他几种选择,但没有成功.

is not helping me. I have tried few other options but no success..

我也在python中使用了simplejson和json包.但是,鉴于文件是错误的json,json.loads(file)会引发错误.

I trioed using simplejson and json package in python too. But given that the files are incorrct json, json.loads(file) throws errors..

相对于python,我现在更喜欢sed.

I would prefer sed over python for now..

推荐答案

 sed -Ei.bak 's/^([[:blank:]]*"EchoTime[^"]*":)"([^"]*)",$/\1\2/' file.json

会做

示例输出

{
    "RepetitionTime": 0.72,
    "TaskName":"WM",
    "Manufacturer": "Siemens",
    "ManufacturerModelName": "Skyra",
    "MagneticFieldStrength": 3.0,
    "EchoTime":0.033
}


注释

  • E以启用扩展的正则表达式.
  • i以启用就地编辑,将创建扩展名为.bak的备份文件.
  • E to enable extended regular expressions.
  • i to enable inplace editing, a backup file with .bak extension is created.

这篇关于使用Sed查找和替换json字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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