Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a file full of unix time strings to human readable dates?

I am processing a file full of unix time strings. I want to convert them all to human readable.

The file looks like so:

1153335401
1153448586
1153476729
1153494310
1153603662
1153640211

Here is the script:

#! /bin/bash
FILE="test.txt"
cat $FILE | while read line; do
perl -e 'print scalar(gmtime($line)), "\n"'
done

This is not working. The output I get is Thu Jan 1 00:00:00 1970 for every line. I think the line breaks are being picked up and that is why it is not working. Any ideas? I'm using Mac OSX is that makes any difference.

like image 501
skymook Avatar asked Dec 09 '22 16:12

skymook


2 Answers

$ perl -lne 'print scalar gmtime $_' test.txt
Wed Jul 19 18:56:41 2006
Fri Jul 21 02:23:06 2006
Fri Jul 21 10:12:09 2006
Fri Jul 21 15:05:10 2006
Sat Jul 22 21:27:42 2006
Sun Jul 23 07:36:51 2006
like image 92
Greg Bacon Avatar answered Dec 30 '22 09:12

Greg Bacon


Because $line is in single quotes, it's not being processed by bash, and so $line is treated as an (undefined) Perl variable rather than a bash variable.

You don't need a while read bash loop; Perl can do the looping itself using its -n option.

perl -nE 'say scalar(gmtime($_))' test.txt

(using -E to enable say, which automatically appends a newline)

like image 42
Josh Kelley Avatar answered Dec 30 '22 09:12

Josh Kelley