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

牧云@^-^@ 提交于 2019-12-04 10:57:42
$ 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

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)

Don't use cat.

#! /bin/bash
file="test.txt"
while read line
do
    date -d @$line
done < "$file"

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.

No need for Perl:

awk '{ print strftime("%c", $0) }' somefile.txt
Zaid

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.

GNU date/xargs solution:

  xargs -i  date -d "1970-01-01 00:00:00 {} seconds"  </tmp/timestamps 

This simple command will do

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

Not forgetting that localtime() can be used instead of gmtime() in Perl

So, if you're not in Greenwich in Winter, you can use localtime(), e.g.

Perl code:

    my $unixtime = 1417014507;
    my $humantime = localtime($unixtime);
    print "\$humantime = $humantime \n";

output:

    $humantime = Wed Nov 26 15:08:27 2014 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!