【问题标题】:Replacing/Inserting Timestamp in a File在文件中替换/插入时间戳
【发布时间】:2017-06-17 20:26:56
【问题描述】:

我有一个 JSON 文件,其中包含以下格式的数据。我正在为德鲁伊编写索引任务以摄取数据。由于时间戳(event_time)而拒绝。

有没有办法将 event_time 值从 2016-11-30 23:59:53.654000 转换为 2016-11-30T23:59:53.654Z?

JSON 文件:

{"app":14232,"device_carrier":"airtel","$schema":10,"city":"Bellary","user_id":"234293","uuid":"1d5b5328-b729-11e2-a0e5-22340a56812f","event_time":"2016-11-30 23:59:53.654000","platform":"Android","os_version":"4.4.2","insider_id":3426766963,"processed_time":"2016-12-01 00:00:05.429064","user_creation_time":"2015-12-14 18:34:04.632000","version_name":"2.08","ip_address":"117.266.132.112","paying":"true","dma":null,"user_properties":{"[SauceFlyer] campaign":"N\/A","[SauceFlyer] media source":"Chemical"},"client_upload_time":"2016-12-01 00:00:03.982000","$insert_id":"e43b2a4d-072f-2322-bd74-6bdb0b2e1f63","event_type":"Search","library":"insider-android\/2.9.2","device_type":"Micromax Owen Nitro","device_manufacturer":"Micromax","start_version":"1.57","location_lng":null,"server_upload_time":"2016-12-01 00:00:04.230000","event_id":286,"location_lat":null,"os_name":"android","insider_event_type":null,"device_brand":"Micromax","groups":{},"event_properties":{"Search Query":"clutches for women"},"data":{},"device_id":"ff71c4f0-81b8-4a44-8db1-1555e22f6761R","language":"English","device_model":"Micromax A310","country":"India","region":"Karnataka","adid":null,"session_id":1480550372776,"device_family":"Micromax Phone","idfa":null,"client_event_time":"2016-11-30 23:59:53.406000"}

【问题讨论】:

    标签: regex linux file replace sed


    【解决方案1】:

    使用 sed 的另一种方法(因为年、月、日、小时、分钟和秒不仅是 [0-9] 数字):

    $ sed 's/\([12][0-9]\{3\}-[01][0-9]-[0-3][0-9]\) \([0-2][0-9]\(:[0-5][0-9]\)\{2\}\.[0-9]\{3\}\)000/\1T\2Z/' <<< "2016-11-30 23:59:53.654000"
    2016-11-30T23:59:53.654Z
    

    【讨论】:

      【解决方案2】:

      如果您的输入在 input.json 中并且您想使用 sed 来完成:

      sed 's/\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\) \([0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\}\.[0-9]\{3\}\)[0-9]\{3\}/\1T\2Z/g' input.json
      

      (是的,我同意这很丑。) 但是,它会替换您输入中的 all 时间戳,假设这是您想要的。如果没有,您必须扩展正则表达式以匹配它之前的键。

      一个等效的 perl 单行“为了更好的可读性”:

      cat input.json | perl -p -e 's/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}.\d{3})\d{3}/\1T\2Z/g'
      

      【讨论】:

      • 我们如何在该时间戳之前包含密钥。例如带有 sed 的 event_time?
      • 谢谢 Jan。知道了。 sed 's/"event_time":.([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}) ([0-9]\ {2\}:[0-9]\{2\}:[0-9]\{2\}\.[0-9]\{3\})[0-9]\{3\}/ "event_time":\1T\2Z/g' sample.json
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      • 2020-03-24
      • 1970-01-01
      相关资源
      最近更新 更多