Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
    
Is it this specific date or all dates with this format? –  Graeme Apr 2 at 19:50

2 Answers 2

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.