简体   繁体   English

在外壳中使用sed从json文件中删除行

[英]delete line from json file with sed in a shell

I would like to delete a line containing "electron-inspector": "0.1.4", from .package.json 我想从.package.json中删除包含"electron-inspector": "0.1.4",

The following is not working. 以下内容不起作用。

sed -i '' -e 'electron-inspector' ./package.json

What do I have to change? 我必须改变什么?

You could do this, but in not a JSON parser ! 您可以执行此操作,但不要在JSON解析器中进行 警告

sed -i '' -e '/electron-inspector/d' file

( -i '' is required for macOS's sed) -i ''是macOS的sed所必需的)

Imagine a simple ( inline ) case like this : 想象一个简单的( 内联 )情况,像这样:

{"foo": 123, "electron-inspector": "0.1.4", "bar": 42 }

BOOOM ! OO! So : 因此:

The proper way, using : 正确的方法,使用

jq -r 'del(.["electron-inspector"])' file.json > _.json && mv _.json file.json

The dash - is a special case for jq 破折号-jq特殊情况

If instead you had a simple case, the command would be : 相反,如果您有一个简单的案例,则命令为:

jq 'del(.electroninspector)' file.json    

Check JQ 检查JQ


Another solution using and... : 另一个使用和...的解决方案...

cat file.json
{"foo": 123, "electron-inspector": "0.1.4", "bar": 42 }

Code : 代码:

$ node<<EOF > _.json && mv _.json file.json                                               
var o = $(< file.json);
delete o["electron-inspector"];
console.log(JSON.stringify(o, null, 4));
EOF

Edited file : 编辑文件:

{
    "foo": 123,
    "bar": 42
}

Last but not least, to edit the file properly using sponge : 最后但并非最不重要的一点是,使用sponge正确编辑文件:

Instead of : > x.json && mv x.json file.json , we can do : 代替: > x.json && mv x.json file.json ,我们可以做:

command ...... file.json | sponge file.json

You need installed. 您需要安装

我可以使用它:

sed -i '/electron-inspector/d' package.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM