I want to add date & time at the begging of each line in some file

I used sed in order to add the date & time before each line in file

please advice what I need to update in my sed in order to support this action ,

I can accept other solution with awk or perl one liner etc ...

# date="[`date +%d"/"%b"/"%G"-"%T`]"
# echo $date
#  sed "s/^/$date /" file     
sed: command garbled: s/^/[21/Feb/2013-14:07:58] /


file before edit


file after edit

 [21/Feb/2013-14:07:58] param1=3478374
 [21/Feb/2013-14:07:58] param2=34128374
 [21/Feb/2013-14:07:58] param3=34783743

or use another separator like "|", i tried it on mac.

$ date="[`date +%d"/"%b"/"%G"-"%T`]"
$ echo $date

$ cat /tmp/a

$ sed "s|^|$date  |g" /tmp/a 
[21/Feb/2013-21:14:15]  param1=3478374
[21/Feb/2013-21:14:15]  param2=34128374
[21/Feb/2013-21:14:15]  param3=34783743

There are too many slashes in that sed command. The ones in your $date variable need to be escaped.

This is what I get (which is a somewhat more useful error message):

> echo foo | sed "s/^/[21/Feb/2013-14:07:58] /"
sed: -e expression #1, char 9: unknown option to `s'
> echo foo | sed "s/^/[21\/Feb\/2013-14:07:58] /"
[21/Feb/2013-14:07:58] foo


date="[`date +%d"\/"%b"\/"%G"-"%T`]"

You may need to double-escape your variable if single-escaping is not enough because the escaping may be removed when the variable is dereferenced:

date="[`date +%d"\\/"%b"\\/"%G"-"%T`]"

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.