views:

210

answers:

8

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.

A: 

No need for Perl:

awk '{ print strftime("%c", $0) }' somefile.txt
Ignacio Vazquez-Abrams
There's no need for awk either. The Perl solution and your awk solution are basically the same thing.
brian d foy
+9  A: 
$ 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
Greg Bacon
A few good answers. I had to give it to gbacon though. This one liner worked a treat. Thanks to all for the help. It would have been better if I didn't mix bash and perl.
skymook
@skymook Thanks! I'm glad it helped.
Greg Bacon
golfed: `perl -lpe '$_=gmtime$_' test.txt`
Eric Strom
+2  A: 

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)

Josh Kelley
or `-lne` for pre-5.10 versions of Perl
Zaid
A: 

The issue is that you haven't assigned anything to the $line variable, so it defaults to a zero-value, which is why you always get Thu Jan 1 00:00:00 1970 as an output.

gbacon's answer is about as slick as it gets in Perl.

Zaid
Thank you, Zaid!
Greg Bacon
A: 

GNU date/xargs solution:

  xargs -i  date -d "1970-01-01 00:00:00 {} seconds"  </tmp/timestamps 
Jürgen Hötzel
+1  A: 

Don't use cat.

#! /bin/bash
file="test.txt"
while read line
do
    date -d @$line
done < "$file"
Dennis Williamson
I have used to fighting `cat` as you but I ceases. I have found it very practical in command line work. `cat foo | grep bar | ...` seems better that `<foo grep bar | ...` and is more flexible than `grep bar foo | ...`
Hynek -Pichi- Vychodil
If you want to get a Useless Use of Cat award, you can't avoid cat.
brian d foy
@brian: I have a shelf full of them.
Dennis Williamson
+1  A: 

It's not the line breaks, it's that the $line inside the Perl script is a different variable than the $line in the bash script. You could try:

perl -e "print scalar(gmtime($line)),qq/\\n/"

Note the double-quotes, which allow bash to do variable interpolation.

mobrule
A: 

This simple command will do

 cat time.txt | while read line; do date -ud @$line; done > string.txt
Manivasagan