Json 使用awk有条件地交换行

Json 使用awk有条件地交换行,json,awk,sed,Json,Awk,Sed,我有以下文件 { "number": "12", "question": "Sample Question", "options": [ { "text": "sample option 1", "type": "check", "isAnswer&qu

我有以下文件

{
  "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交换一些行,但没有得到预期的结果。这似乎是一个有趣的问题,有人能帮忙吗?

我通过以下命令解决了这个问题

awk -v r="text" -v o="type" ' $0 ~ o { s = 1 } $0 ~ r && ! s { cur = $0; getline; print; print cur; next; }  1 ' file.json
这可能适用于您(GNU-sed):

如果
“text”:
后面的行包含
“type”:
,请交换这些行


注意:如果文件后面有多行包含
“type”:
,则这可能会使
“text”:
行在文件下面波动。

您有JSON数据。考虑使用<代码> JQ>代码>进行解析和筛选。另外,重新排序JSON字段的目的是什么?谢谢,
jq
是一个很好的建议,我仍在探索这一点。重新排序没有实际用途,因为在解析器方面,它将以预期的格式可读,这只是为了提高可读性。因为您使用了
sed
标记,但在titel中指定了
awk
,所以我只建议使用'sed'/^*“text/{h;d;};/^*”如果在任何其他上下文中出现
文本
类型
,则键入/G'将失败(例如
“解释”:“这是某种类型的文本解释”
)。另外,请参阅以了解何时/如何正确使用
getline
$ awk '$1~/^"text"/{txt=$0; next} {print} txt{print txt; txt=""}' file
{
  "number": "12",
  "question": "Sample Question",
  "options": [
    {
      "type": "check",
      "text": "sample option 1",
      "isAnswer": "false"
    },
    {
      "type": "check",
      "text": "sample option 2",
      "isAnswer": "false"
    },
    {
      "type": "check",
      "text": "sample option 3",
      "isAnswer": "true"
    },
    {
      "type": "check",
      "text": "sample option 4",
      "isAnswer": "true"
    },
    {
      "type": "check",
      "text": "sample option 5",
      "isAnswer": "false"
    }
  ],
  "explanation": "sample explanation",
  "reference": "sample ref"
}
sed -E '/"text":/{N;/"type":/s/(.*)\n(.*)/\2\n\1/;P;D}' file