I have a file "tmp.txt" looking like that:
random text random text 25/06/2021 15:15:15
random text random text 26/06/2021 15:15:15
random text random text 26/06/2021 15:15:15
and I would like to:
- extract all datetimes
- add 4 hours
- display them as timestamp
I didn’t figured out yet how to add hour as I,m facing an issue with the date format not being recognized by the date function.
(I would like to be able to do it with a single line command if possible)
Here is my current command:
egrep -o "[0-9]{2}/[0-9]{2}/[0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}" tmp.txt | while read -r line ; do echo $(date -d "$line" +%s);done
Help appreciated!
2
Answers
Let me adjust the timestamps to make the output more interesting:
@jhnc has the right idea: use a language that’s both good at text manipulation and can do date arithmetic. I’d use Time::Piece
Or, here’s perl piping into xargs for the date stuff
Tried and Tested, Minimal Solution
You can use the below command line to get the desired result. I have tested it with your example and it worked as expected on my Linux machine.
I’ll break it down into multiple lines so it’s easy to understand:
To add 4 hours, you can just mention it after the datetime in -d option as shown above, I tried with hours, minute and days and it worked as expected
For your input file tmp.txt:
On running my command, the output was:
I tested it with edge cases like close to midnight time, leap years etc and it worked fine