替换文件中不属于搜索模式的特定字符串,但在后续文件

时间:2015-10-14 09:17:23

标签: sed grep sh

我有一个配置文件,如下例所示。

{
    "view": "pagelogfile",
    "text": "menu_logFile",
    "disabled": false,
    "icon": null,
    "cls": "treelevel2",
    "iconCls": null,
    "users": ["admin", "guest"],
    "expanded": null,
    "leaf": true,
    "data": []
},
{
    "view": "pagemyfeature",
    "text": "menu_myFeature",
    "disabled": false,
    "icon": null,
    "cls": "treelevel2",
    "iconCls": null,
    "users": ["admin", "guest"],
    "expanded": null,
    "leaf": true,
    "data": []
}

某些用户无法使用某些配置选项,具体取决于HardwareId。例如,视图:pagemyfeature不适用于用户来宾。我必须删除用户" guest"来自"用户数组。由于相同的用户数组在配置文件中出现了几次,我只想在一个地方将其更改为"users": ["admin"],我唯一的搜索模式是menu_myFeature以获取该菜单的正确配置数组。如何更改此数组的后续行?

这就是我想要的样子

{
    "view": "pagelogfile",
    "text": "menu_logFile",
    "disabled": false,
    "icon": null,
    "cls": "treelevel2",
    "iconCls": null,
    "users": ["admin", "guest"],
    "expanded": null,
    "leaf": true,
    "data": []
},
{
    "view": "pagemyfeature",
    "text": "menu_myFeature",
    "disabled": false,
    "icon": null,
    "cls": "treelevel2",
    "iconCls": null,
    "users": ["admin"],
    "expanded": null,
    "leaf": true,
    "data": []
}

使用sed格式化页面功能以及字符串替换不是问题。但是如何确保稍后更换字符串6行?

1 个答案:

答案 0 :(得分:0)

如果你真的想在sed做,那就试试吧。有许多工具可用于json

sed '/{/{:loop; N; /pagemyfeature/{:loop2; N; /users/s/,\? *"guest"//g; b loop2;}; /}/b; b loop;}' yourfile

更易读的格式:

/{/{
    :loop; 
    N; 
    /pagemyfeature/{
        :loop2; 
        N; 
        /users/s/,\? *"guest"//g; b loop2;
    };

    /}/b;

    b loop;
}