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)}'
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
^^^^^^^^^^
$ cat a
2012-05-06 12:12
2012-05-06 12:13
$ while read mydate; do date -d "$mydate" "+%s"; done < a
1336299120
1336299180
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"
$ cat a | grep 2 | xargs -i date -d "{}" "+%s" # grep here is just a silly example
1336299120
1336299180
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With