如何从日志文件中分割日期和时间?

时间:2016-05-16 06:07:47

标签: shell unix awk sed grep

我想显示以空格分隔的日期和时间。 test.log文件还包含许多其他信息。

grep -E '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}T[[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}' test.log

test.log

2016-03-02T10:23:16
2016-03-02T10:23:16
2016-03-02T10:23:16
2016-03-02T10:23:16
2016-03-02T10:23:36
2016-03-02T10:23:36
2016-03-02T10:23:36
2016-03-02T10:23:36
2016-03-02T10:23:36
2016-03-02T10:23:36
2016-03-02T10:23:36
2016-03-02T10:24:35

输出应为

2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:24:35

3 个答案:

答案 0 :(得分:1)

$ awk -F 'T' '{print $1, $2}' test.log 
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:24:35

$ sed 's/T/ /' test.log 
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:24:35

$ tr "T" " " < test.log 
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:24:35

编辑:

由于您在一行中有空格分隔的字段,请取第1个字段并删除括号以获取如下所示的日期和时间:

$ awk '{gsub(/^[\s\[]*|[\s*\]]*$/, "", $1); print $1}' <<< "[2016-02-24T19:59:41.584+00:00] [userId: <anonymous>] [ecid: 005B8a1_^kLDoYUO26L6hz0002S700031R,0:3] [APP: clarientloginga] [DSID: 0000LCKpi5C7y0a_lLK6yZ1MmtvP00006z] [SRC_CLASS: com.dtcc.iam.login.servlet.PostAuthnServlet] [SRC_METHOD: doGet] RETURN" | tr 'T' ' '
2016-02-24 19:59:41.584+00:00

答案 1 :(得分:0)

简单tr命令可以完成这项工作:

tr 'T' ' ' < file

2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:24:35

答案 2 :(得分:0)

您可以将cutT一起用作输入分隔符,并将空格定义为输出分隔符:

$ cut -d T --output-delimiter=' ' -f 1,2 test.log
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:16
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:23:36
2016-03-02 10:24:35