首页 > 解决方案 > 使用 awk 有条件地交换行

问题描述

我有以下文件,

{
  "number": "12",
  "question": "Sample Question",
  "options": [
    {
      "text": "sample option 1",
      "type": "check",
      "isAnswer": "false"
    },
    {
      "text": "sample option 2",
      "type": "check",
      "isAnswer": "false"
    },
    {
      "text": "sample option 3",
      "type": "check",
      "isAnswer": "true"
    },
    {
      "text": "sample option 4",
      "type": "check",
      "isAnswer": "true"
    },
    {
      "text": "sample option 5",
      "type": "check",
      "isAnswer": "false"
    }
  ],
  "explanation": "sample explanation",
  "reference": "sample ref"
}

我想以type之前的方式重新排序这些行text

   {
      "type": "check",
      "text": "sample option 1",
      "isAnswer": "false"
    }

我知道这是可行的,我可以使用 awk 交换一些行,但没有得到想要的结果。这似乎是一个有趣的问题,有人可以帮忙吗?

标签: jsonawksed

解决方案


我可以使用以下命令解决此问题。

awk -v r="text" -v o="type" ' $0 ~ o { s = 1 } $0 ~ r && ! s { cur = $0; getline; print; print cur; next; }  1 ' file.json

推荐阅读