替换JSON配置文件中的日期

时间:2017-01-27 13:46:18

标签: linux bash date sed

我是新手,但试图让新脚本运行,但我需要它在今天的日期作为配置文件中的变量调用,以便程序可以运行。

我确信到目前为止,最好的方法是实现它,这一行将取代我需要的配置文件的正确部分,但我无法弄清楚如何使用“今天的日期”,例如日期+%F命令。

sed -i 's/"to_date":.*/"to_date":"date +%F"/' /config/settings

配置如下:

{
 "username":"admin",
 "password":"redhat",
 "assumeyes":true,
 "to_date": "2011-10-01",
 "skip_depsolve":false,
 "skip_errata_depsolve":false,
 "security_only":false,
 "use_update_date":false,
 "no_errata_sync":false,
 "dry_run":false,
 "errata": ["RHSA-2014:0043", "RHBA-2014:0085"],
 "blacklist": {
              },
 "removelist": {
              },
 "channels":[
             {
                "rhel-x86_64-server-5": {
                    "label": "my-rhel5-x86_64-clone",
                    "existing-parent-do-not-modify": true
                },
                "rhn-tools-rhel-x86_64-server-5": {
                    "label": "my-tools-5-x86_64-clone",
                    "name": "My Clone's Name",
                    "summary": "This is my channel's summary",
                    "description": "This is my channel's description"
                }
             },
            {
                "rhel-i386-server-5": "my-rhel5-i386-clone"
             }
           ]
}

2 个答案:

答案 0 :(得分:3)

使用JSON parser jq jq download and usage $helper->table = $this->table; $helper->identifier = $this->identifier; 字段来传递当前日期

protected $table = 'module';

{{3}}说明非常简单。建议使用它来操纵--arg,而不是依赖jq --arg inputDate $(date +%F) '.to_date = $inputDate' /config/settings { "username": "admin", "password": "redhat", "assumeyes": true, "to_date": "2017-01-27", "skip_depsolve": false, "skip_errata_depsolve": false, "security_only": false, "use_update_date": false, "no_errata_sync": false, "dry_run": false, "errata": [ "RHSA-2014:0043", "RHBA-2014:0085" ], "blacklist": {}, "removelist": {}, "channels": [ { "rhel-x86_64-server-5": { "label": "my-rhel5-x86_64-clone", "existing-parent-do-not-modify": true }, "rhn-tools-rhel-x86_64-server-5": { "label": "my-tools-5-x86_64-clone", "name": "My Clone's Name", "summary": "This is my channel's summary", "description": "This is my channel's description" } }, { "rhel-i386-server-5": "my-rhel5-i386-clone" } ] }

JSON不会就地编辑文件,将其保存到临时文件并使用regex

将其重命名
jq

答案 1 :(得分:0)

要在一些带引号的文本中包含命令的输出,您必须使用子shell并使用双引号,以便文本将被扩展:

sed -i "s/\"to_date\":.*/\"to_date\":\"$(date +%F)\"/" /config/settings

我也是第二个Inian的评论:你应该使用jq来操纵JSON数据。

例如,以下命令应该进行所需的修改:

jq ".toDate = $(date +%F)" /config/settings