I'm making a script using BASH that greps the timestamp from a file (~/logs/Server_Info.log). Specifically, I want to pull the hour digit from the timestamp and record it onto a variable.

This is the format I used for the timestamp:

date +"%b-%d-%Y-%I:%M:%S %p"

And I used this script to pull the data:

LAST_HOUR="$(( $(date +%I) - 1 ))"
SEARCH_STRING=$(date +"%b-%d-%Y-${LAST_HOUR}:")

timeval=$(grep "${SEARCH_STRING}" ~/logs/Server_Info.log)
echo "$timeval"

exit 0

However, whenever I execute this script, I either get two answers:

Blank output



which was completely wrong, because my timestamp is

Mar-24-2017-05:07:00 PM 

With awk, it's something like:

$ var=$(date +"%b-%d-%Y-%I:%M:%S %p" | awk -F[-:] '{print $4}') && echo $var
$ var=$(date +"%b-%d-%Y-%I:%M:%S %p" | awk -F[-:] '{print $4 - 1}') && echo $var

Log file contains date format in 2017-03-15T08:00:23.698411Z format. If this timing is in UTC which is 2017-03-15T08:00:23.698411Z(time and date is 08:00:23 and 2017-03-15) and you need to convert it in IST. Use below command for last hour

date -d '2017-03-15T08:00:23.698411Z last hours' -u +%s


date -d @1489561223 +"%Y/%m/%d-%H:%M:%S"


want to go back 2 hours ago,then use "2 hours ago" instead of "last hours".

Note:- I am running above command in linux server and my linux server timing is in UTC.If you want to run above command in IST linux server,then you have to add another 5 hours 30 minutes(eg:- "6 hours 30 minutes ago" instead of "last hours").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.