bash 使用 sed 或 awk 查找和替换 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26281538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:30:31  来源:igfitidea点击:

Find and replace for JSON with sed or awk

jsonbashawksed

提问by samdunne

So I need to be able to inject a value into JSON using sed or awk (preferably on one line) and I cannot install any external libraries to help me.

所以我需要能够使用 sed 或 awk(最好在一行中)将一个值注入到 JSON 中,并且我无法安装任何外部库来帮助我。

An example of the json is something like {"version":"0.5363"}

json 的一个例子是这样的 {"version":"0.5363"}

I'd need to be able to inject a new value for version.

我需要能够为版本注入新值。

Any help would be greatly appreciated.

任何帮助将不胜感激。

采纳答案by Avinash Raj

You could try the below sed command,

你可以试试下面的 sed 命令,

$ echo '{"version":"0.5363"}' | sed 's/\({"version":"\)[^"]*\("}\)/newvalue/g'
{"version":"newvalue"}

In the above sed command, replace the newvaluewith value you want. Add inline edit option -ito save the changes made.

在上面的 sed 命令中,用newvalue你想要的值替换。添加内联编辑选项-i以保存所做的更改。

sed -i 's/regex/replacement/g' file