2

I have script that returns a list of files with the full path to each file. For e.g. - root/folder/file@1610565763436. Hence, the output looks like

/root/folder/file@1610565763436
/root/folder/file@1610568241000
/root/folder/file@1610597041000
/root/folder/file@1610625841000
/root/folder/file@1610654641000
/root/folder/file@1610683441000
/root/folder/file@1610712242000
/root/folder/file@1610741041000
/root/folder/file@1610769841000
/root/folder/file@1610798641000
/root/folder/file@1610827441000
/root/folder/file@1610856241000
/root/folder/file@1610885041000
/root/folder/file@1610913841000

I want to format the output such that I get the human readable timestamp as the output only. I tried doing a cut -d "@" -f 2 to get the timestamp but piping that to a xargs and running a date command does not work, for me. i.e. /bin/bash scriptToGetFiles | cut -d "@" -f 2 | xargs date -d {}.

FWIW, running the above with xargs -t returns an error

date -d @ 1610565763436 1610568241000 1610597041000 1610625841000 1610654641000 1610683441000 1610712242000 1610741041000 1610769841000 1610798641000  
date: extra operand ‘1610568241000’

I'd appreciate any suggestions or pointers.

1
  • pipe it to cut -f2 -d@ | cut -c1-10 | perl -lape '$_=localtime($_)' to do it without forking date. Useful if you have, say, hundreds of such lines.
    – user339730
    Jan 25, 2021 at 3:47

2 Answers 2

1

With GNU date:

$ echo /root/folder/file@1610565763436 | cut -d@ -f2 | xargs -I '{}' echo {} / 1000  | bc  | xargs -I '{}' date --date=@{}
Wed Jan 13 20:22:43 CET 2021

On FreeBSD:

$ echo /root/folder/file@1610565763436 | cut -d@ -f2 | xargs -I '{}' echo {} / 1000  | bc  | xargs  date -r
Wed Jan 13 20:22:43 CET 2021 
0
0

With plain bash, printf can format Epoch times:

processThatOutputsStuff | while IFS=@ read -r path date; do
    printf '%(%c)T\n' "${date%???}"
done

${date%???} is a parameter expansion that removes the last 3 characters from the variable's value.

If you want a different datetime format, replace %c.

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.