29

I have a date like 2014-01-30 05:04:27 GMT, and if I run date -d "2014-01-30 05:04:27 GMT", the output is in my server's timezone (Thu Jan 30 16:04:27 EST 2014).

With the use of grep and cut, I have extracted the date in GMT from a file. However, I am struggling to then convert this into my local time.

For example:

grep "something" logfile.txt | grep "Succeeded" | cut -f1 -d'['

Output: 2014-01-30 05:04:27 GMT

What can I add on the end, to pass that output to date -d?

Attempted:

grep "something" logfile.txt | grep "Succeeded" | cut -f1 -d'[' | date -d
grep "something" logfile.txt | grep "Succeeded" | cut -f1 -d'[' | date
grep "something" logfile.txt | grep "Succeeded" | cut -f1 -d'[' | date -d "$1"

3 Answers 3

26
gmt="$(grep "something" logfile.txt | grep "Succeeded" | cut -f1 -d'[')"
date -d "$gmt"

Or, if you prefer the pipeline format:

grep "something" logfile.txt | grep "Succeeded" | cut -f1 -d'[' | { read gmt ; date -d "$gmt" ; }

The problem is that date does not use stdin. Thus, we have to capture the stdin into a variable (called gmt here) and then supply that on the command line to date.

Sample output from the second approach:

$ echo  "2014-01-30 05:04:27 GMT" | { read gmt ; date -d "$gmt" ; }
Wed Jan 29 21:04:27 PST 2014
2
  • 1
    Thank you, this solved the problem! Also appreciate you explaining the reason behind why it wasn't working. Feb 4, 2014 at 2:40
  • 1
    I have used the -f option, but your answer with the pipeline format is very elegant! Jul 19, 2021 at 9:15
29

If you're using GNU date from a sufficiently recent coreutils, there's date -f, from the help screen:

-f, --file=DATEFILE       like --date once for each line of DATEFILE

So your attempt 4 could have been:

$ grep "something" logfile.txt | grep "Succeeded" | cut -f1 -d'[' | date -f -

the last - stands for stdin.

5
  • 5
    This should be the accepted answer.
    – Petrus K.
    Feb 13, 2017 at 13:16
  • Is it possible to compare the output of the above command to a particular date. Eg. I need to list all dates older than "Wed Jan 30 21:04:27 PST 2014"
    – Manu
    Dec 29, 2017 at 7:26
  • @Manu not per se, dateutils have dategrep for that specific use case.
    – hroptatyr
    Dec 29, 2017 at 19:54
  • This is so much easier! If only I could read I might have found this in he man page.
    – Ken Sharp
    May 2, 2018 at 3:34
  • how do you pair this with timestamp parsing, e.g. date --date @<timestamp>
    – Animismus
    Jun 19, 2023 at 9:02
3

Just use stdin as file:

command | date --file=-
1
  • 1
    Please add an explanation why this works, preferably with documentation links.
    – Glorfindel
    Jan 2, 2023 at 22:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .