如何在bash中使用grep命令解析以下日期

在 json 文件中给定日期,"ts":"2021-04-23T13:11:57Z"或者"2021-05-05T07:22:54+05:00"我想使用 grep 读取字符串。

需要帮助形成最后一部分的正则表达式,即时区。

我当前的命令
grep -Po '"ts":"K([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]+Z对于第一种格式来说很好用,我该如何修改它以使其适用于两种格式。

回答

使用您显示的带有 GNUgrep的 PCRE 选项的示例,您可以尝试遵循正则表达式来匹配两个时间。

grep -oP '(?:"ts":)?"d{4}-d{2}-d{2}T(?:[0-1][1-9]|2[0-4]):(?:[0-4][0-9]|5[0-9])[+:](?:[0-4][0-9]|5[0-9])(?:Z"|+(?:[0-4][0-9]|5[0-9]):(?:[0-4][0-9]|5[0-9])")' Input_file

说明:为以上添加详细说明。

(?:"ts":)?                ##In a non-capturing group matching "ts": keeping it optional here.
"d{4}-d{2}-d{2}T       ##Matching " followed by 4 digits-2digits-2digits T here.
(?:                       ##Starting 1st non-capturing group here.
   [0-1][1-9]|2[0-4]      ##Matching 0 to 19 and 20 to 24 here to cover 24 hours.
):                        ##Closing 1st non-capturing group followed by colon here.
(?:                       ##Starting 2nd non-capturing group here.
   [0-4][0-9]|5[0-9]      ##Matching 00 to 59 for mins here.
)                         ##Closing 2nd non-capturing group here.
[+:]                      ##Matching either + or : here.
(?:                       ##Starting 3rd capturing group here.
   [0-4][0-9]|5[0-9]      ##Matching 00 to 59 for seconds here.
)                         ##Closing 3rd non-capturing group here.
(?:                       ##Starting 4th non-capturing group here.
   Z"|+                  ##Matching Z" OR +(literal character) here.
   (?:                    ##Starting non-capturing group here.
     [0-4][0-9]|5[0-9]    ##Matching 00 to 59 here.
   )                      ##Closing non-capturing group here.
   :                      ##Matching colon here.
   (?:                    ##Starting non-capturing group here.
     [0-4][0-9]|5[0-9]    ##Matching 00 to 59 here.
   )"                     ##Closing non-capturing group here, followed by "
)                         ##Closing 4th non-capturing group here.


以上是如何在bash中使用grep命令解析以下日期的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>