有条件的sed用grep

时间:2017-04-05 12:25:33

标签: bash sed grep jq

我想使用有条件地将团队名称更改为水果,如果下面一行中的食物包含字
raspberry
strawberry
apple
但如果搜索不匹配则不管它。以下文件内容的示例:

{
"team":"veg",
"food":"raspberry",
},
{
"team":"veg",
"food":"carrot",
},
{
"team":"veg",
"food":"strawberry",
}

很高兴使用其他工具,如果它更适合:)我将替换文件(理想情况下),因此可能需要使用-i标志的sed。

由于

1 个答案:

答案 0 :(得分:4)

我们是 jq 方法:

有效的json输入应该是(让我们说test.json):

[
  {
    "team": "veg",
    "food": "raspberry"
  },
  {
    "team": "veg",
    "food": "carrot"
  },
  {
    "team": "veg",
    "food": "strawberry"
  }
]
jq 'map(select(.food == "strawberry" or .food == "raspberry" or .food == "apple").team |="fruit")' test.json

输出:

[
  {
    "team": "fruit",
    "food": "raspberry"
  },
  {
    "team": "veg",
    "food": "carrot"
  },
  {
    "team": "fruit",
    "food": "strawberry"
  }
]
  

map(x)对于任何过滤器 x map(x)将为每个过滤器运行   输入数组的元素,并以新数组

返回输出

|="fruit" - 更新作业https://stedolan.github.io/jq/manual/#Assignment