使用shell替换特定行之后的单词

时间:2018-01-19 10:21:14

标签: json shell awk sed replace

我在json文件中有以下几行

 {"name":"images",
 "enable":1,
 "binary_path":"/usr/bin/docker",
 "parameter":"images"
},
{"name":"pull",
  "enable":1,
  "binary_path":"/usr/bin/docker",
  "parameter":"pull httpd"
 },

我想替换

"enable":1,

"enable":0, 

的json的

"name":"pull"

我尝试了以下代码

sed -i '/"name":"pull",/a "enable":0' test.json

4 个答案:

答案 0 :(得分:4)

正确的方法是使用jq之类的特定 json 解析器:

示例test.json

[
  {
    "name": "images",
    "enable": 1,
    "binary_path": "/usr/bin/docker",
    "parameter": "images"
  },
  {
    "name": "pull",
    "enable": 1,
    "binary_path": "/usr/bin/docker",
    "parameter": "pull httpd"
  }
]
jq '[.[] | if .name == "pull" then .enable=0 else . end]' test.json

输出:

[
  {
    "name": "images",
    "enable": 1,
    "binary_path": "/usr/bin/docker",
    "parameter": "images"
  },
  {
    "name": "pull",
    "enable": 0,
    "binary_path": "/usr/bin/docker",
    "parameter": "pull httpd"
  }
]

答案 1 :(得分:2)

我们可以简单地在sed中使用line运算符来实现这一点。请尝试以下,

sed '/"name":"pull"/{n;s/.*/"enable":0,/}' test.json

在源文件中添加-i选项进行编辑,

sed -i '/"name":"pull"/{n;s/.*/"enable":0,/}' test.json

答案 2 :(得分:2)

awk解决方案

awk '/name":"pull/{a=1;print $0;next}a==1{$0="\"enable\""":""0" ;print $0;a=0;next}1  test.json

答案 3 :(得分:1)

这对我有用 -

干跑 -

$ sed '/"name":"pull"/!b;n;c\ \"enable":0,' test.json

使用-i -

更改文件

$ sed -i '/"name":"pull"/!b;n;c\ \"enable":0,' test.json

输出 -

# sed '/"name":"pull"/!b;n;c\ \"enable":0,' test.json

 {"name":"images",
 "enable":1,
 "binary_path":"/usr/bin/docker",
 "parameter":"images"
},
{"name":"pull",
 "enable":0,
  "binary_path":"/usr/bin/docker",
  "parameter":"pull httpd"
 },