Extract date from log file

2019-09-20 15:25发布

I have a log line like this:

Tue Dec  2 10:03:46 2014 1 10.0.0.1 0 /home/test4/TEST_LOGIN_201312021003.201412021003.23872.sqlLdr b _ i r test4 ftp 0 * c

And I can print date value of this line like this.

echo $log | awk '{print $9}' | grep -oP '(?<!\d)201\d{9}' | head -n 1

I have another log line like this, how can I print date value?

Tue Dec  9 10:48:13 2014 1 10.0.0.1 80 /home/DATA1/2014/12/11/16/20/blablabla_data-2014_12_11_16_20.txt b _ i r spy ftp 0 * c

I tried my awk/grep solution, but it prints 201 and 9 number after 201 when see 201.

Sub folders and data name is the same:

2014/12/11/16/20 --> 11 Dec 2014 16:20 <-- blablabla_data-2014_12_11_16_20.txt

note: /home/DATA1 is not static. year/month/day/hour/minute is static.

标签: bash date awk grep
2条回答
叛逆
2楼-- · 2019-09-20 15:52

sed can also work too, if you are acquainted with it

echo "Tue Dec  9 10:48:13 2014 1 10.0.0.1 80 /home/DATA1/2014/12/11/16/20/blablabla_data-2014_12_11_16_20.txt b _ i r spy ftp 0 * c"|sed  's#.*[[:alnum:]]*/\([[:digit:]]\{4\}/[[:digit:]]\{2\}/[[:digit:]]\{2\}/[[:digit:]]\{2\}/[[:digit:]]\{2\}\).*#\1#'

output

2014/12/11/16/20

To remove "/", the same above command piped to tr -d '/'

Full command line

echo "Tue Dec  9 10:48:13 2014 1 10.0.0.1 80 /home/DATA1/2014/12/11/16/20/blablabla_data-2014_12_11_16_20.txt b _ i r spy ftp 0 * c"|sed  's#.*[[:alnum:]]*/\([[:digit:]]\{4\}/[[:digit:]]\{2\}/[[:digit:]]\{2\}/[[:digit:]]\{2\}/[[:digit:]]\{2\}\).*#\1#'|tr -d '/'

Output

201412111620
查看更多
Lonely孤独者°
3楼-- · 2019-09-20 15:57

As the format in the path is /.../YYYY/MM/DD/HH/MM/filename, you can use 201D/DD/DD/DD/DD in the grep expression to match the date block:

$ log="Tue Dec  9 10:48:13 2014 1 10.0.0.1 80 /home/DATA1/2014/12/11/16/20/blablabla_data2_11_16_20.txt b _ i r spy ftp 0 * c"
$ echo "$log" | grep -oP '(?<!\d)201\d/\d{2}/\d{2}/\d{2}/\d{2}'
2014/12/11/16/20

And eventually remove the slashes with tr:

$ echo "$log" | grep -oP '(?<!\d)201\d/\d{2}/\d{2}/\d{2}/\d{2}' | tr -d '/'
201412111620
查看更多
登录 后发表回答