writing the timestamp to as a header in a file

hello mates,

         this is my first post. please help me out. i have got a file with some data in it. i am asked to write the timestamp as a header for that file. i mean the time the file created should be mentioned at the top of the file. i know we can use sed to insert a sentence but don't know how to insert the date there. please help me out. its a matter of urgency. 

regards

Depends a bit on a few things. If you have a command foo let's say, that writes data to standard out, and you are capturing the data and want it timestamped, then something like this (assuming you are using ksh or bash):

(date; foo) >output-file

This will write the date and then the output from foo to the named file. You can give any parameters to date and/or foo that are needed.

If your file already exists, and you want to add the current time (assuming it was created by a previous command so current time is nearly the creation date of the data), and the above won't work because maybe the command creates the file and doesn't write to standard ouput, then something like this might work:

(date; cat orig-file) >new-file && mv new-file orig-file

This will create a new file with the date, add the contents from the original file, and if that operation was successful, will move the new file 'on top' of the original file.

Fantastic mate. i was looking for the second option and it works out for me. thanks a lot. but when i use the mv command, it is asking me whether to move it or not. can't we stop the shell asking this question and mv the file name automatically. may be i may have to write a script for this. isn't it? i am new to unix and not upto the standards of scripting. just a novice. any how thanks for the quick reply mate. if possible could you please explain the command. it works but i don't understand it properly.

Use -f option

man mv

HTH
--ahamed

1 Like

agama and ahamed101, thank you both. -f tip is very useful as well.

regards

The parentheses cause all of the commands to be run in a sub-shell. As such, the standard output from all of the commands goes to the same place so (command1; command2) >file nicely writes all of the output with the header line as you wanted. The && causes the next command on the line to be executed only if the previous command (the sub-shell) executed and returned a good return code. Thus, the move command is run only if the tmp file was successfully created. This prevents overlaying the original file with potentially bad data in the tmp file if the command failed. This is important if the data is difficult to, or cannot be, recreated.

Hope this helps you understand.

thanks for the explanation mate. now it makes sense to me. thanks a lot.