1

I've looked through several tutorials and a couple of StackOverflow posts, but I've not seen any examples using sed or awk which use dates. I have a text file that contains this as the first line, I need to replace the date with the current date and time via script; what is the easiest way to do this in Linux?

TS: 2014-03-31 13:56:01

I can use any tool available in a standard Ubuntu install such as sed or awk.

  • Is it this specific date or all dates with this format? – Graeme Apr 2 '14 at 19:50
4

The simplistic approach would be to just use sed and replace the string with the correct one. So, if the current time is 2014-04-02 21:34:13 you could simply run

sed 's/2014-03-31 13:56:01/2014-04-02 21:34:13/' file

Since, presumably, you want to do this dynamically, you can pass sed the result of the relevant date call instead:

sed "s/2014-03-31 13:56:01/$(date '+%F %T')/" file

Note the double quotes (") around the sed command, those are needed for the date command to be run.

3

To replace the first line with the expected timestamp, just use

sed "1c TS: $(date '+%F %T')"

The 1 at the beginning means the first line, c means "replace the line with the following string". $(...) inserts the output of the given command, see man date for details.

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.