Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

bash - Extract date from log file

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)201d{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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)201d/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)201d/d{2}/d{2}/d{2}/d{2}' | tr -d '/'
201412111620

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...