Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping to UNIX date function

Tags:

date

unix

To format a date to timestamp, I'd use eg date -d "2012-05-06 12:12" "+%s". But if I have a file with date per line how could I do something like:

cat file.txt | date "+%s" # does not work

I could do the following:

cat file.txt | while read line; do `date -d "$line" "+%s"`; done;

but this is utterly ugly...

Other solution converting date-time to timestamp (in format YYYY-MM-DD HH:MM:SS) is acceptable as well.

Edit: My real life example is a bit more complex, let me elaborate:

`some command that produces complex lines` | grep only-speicif-lines | awk '{ print $5 | (I WANT TO PASS THE DATE HERE TO GET TIMESTAMP IN THE END)}'
like image 575
ddinchev Avatar asked Jan 13 '23 15:01

ddinchev


1 Answers

This makes it:

while read mydate
do
  date -d "$mydate" "+%s"
done < file

Note that your solution

cat file.txt | while read line; do `date -d "$line" "+%s"`; done;

is not the way to read a file line per line. You need to

while read line; do `date -d "$line" "+%s"`; done < file.txt
                                                  ^^^^^^^^^^

Test

$ cat a
2012-05-06 12:12
2012-05-06 12:13
$ while read mydate; do date -d "$mydate" "+%s"; done < a
1336299120
1336299180

Update

From your comment:

Edit: My real life example is a bit more complex, let me elaborate:

`some command that produces complex lines` | grep only-speicif-lines | awk '{ print $5 | (I WANT TO PASS THE DATE HERE

TO GET TIMESTAMP IN THE END)}'

This can make it:

xargs -i date -d "{}" "+%s" 

Test

$ cat a | grep 2 | xargs -i date -d "{}" "+%s"  # grep here is just a silly example
1336299120
1336299180
like image 55
fedorqui 'SO stop harming' Avatar answered Jan 31 '23 08:01

fedorqui 'SO stop harming'