json - 使用 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 交换一些行,但没有得到想要的结果。这似乎是一个有趣的问题,有人可以帮忙吗?
解决方案
我可以使用以下命令解决此问题。
awk -v r="text" -v o="type" ' $0 ~ o { s = 1 } $0 ~ r && ! s { cur = $0; getline; print; print cur; next; } 1 ' file.json
推荐阅读
- amazon-web-services - ECS 服务 (AWS) 上的“DeploymentLimitExceededException”
- java - 这三个非常相似的 LinkedList 方法背后的目的是什么?
- jenkins - 是否有任何一个设置完成了本地 travis ci 进程
- node.js - 显示来自 multer 的图像和类型为 uploads / files.jpg 的数据库
- python - 用 geopandas 和 geoplot [Python] 绘制多边形
- reactjs - 如何在其他组件中使用 ViroReact 函数?
- firebase - indexOn 用于嵌套数据 Firebase
- git - Jenkins:如何为管道作业的更改轮询设置忽略路径?
- java - 将字符串集合转换为用户集合。有一个方法 userService.findById()
- python - Python 在插入列表之前按 ID 搜索对象