[DATE][AWK] Working with date and time is a common task for ev | LinuxCheatSheet
[DATE][AWK] Working with date and time is a common task for everyone. There are different tools to do it with Linux, most common one is date
~]$ date -d "2018/01/17 20:01:37" +%s 1516215697 ~]$ date -d @1516215697 +"%Y/%m/%d %H:%M:%S" 2018/01/17 20:01:37 ~]$
You can format date output as you need using + option followed by date format specifier (man date). The -d option allow you to see the date you specify, not the current system time. Please note that -d support relative dates, like ~]$ echo -n "Now: "; date Now: Thu Jan 18 13:38:45 CET 2018 ~]$ echo -n "Yesterday: "; date -d "1 day ago" Yesterday: Wed Jan 17 13:39:07 CET 2018 ~]$ echo -n "Future: "; date -d "+ 3 weeks" Future: Thu Feb 8 13:39:38 CET 2018 ~]$
This can be useful in different ways when scripting, usually when you want to obtain a time range relative to the current time to perform some action. Another way to manipulate date and time is through AWK. Have a look to mktime and strftime. ~]$ echo | awk '{print mktime("2018 01 17 20 01 37")}' 1516215697 ~]$ echo | awk '{print strftime("%Y/%m/%d %H:%M:%S",1516215697)}' 2018/01/17 20:01:37 ~]$
Last but not least, you can even mix awk and date command. This is useful for example when you have a log with date in a certain format and you want to transform it to another one for any reason (i.e. sorting, or extracting a time range). This is the base syntax to use date inside awk: ~]$ echo | awk '{"date" | getline d; print d}' Wed Jan 17 21:59:12 CET 2018 ~]$
Have a look at this example of transformation of apache common log format.
I hope you like it! Please vote for the channel or share it https://tchannels.me/c/linuxcheatsheet http://www.telegramitalia.it/linuxcheatsheet/
This channel is dedicated to broadcast linux suggestions, tricks on the command line, and black magic done with the shell. It is inspired to the (now closed) portico.org web site. The channel post wil...