Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
[21/Feb/2013-14:07:58]
#  sed "s/^/$date /" file     
sed: command garbled: s/^/[21/Feb/2013-14:07:58] /

example

file before edit

 param1=3478374
 param2=34128374
 param3=34783743

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
share|improve this question

2 Answers 2

up vote 3 down vote accepted

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

$ date="[`date +%d"/"%b"/"%G"-"%T`]"
$ echo $date
[21/Feb/2013-21:17:22]

$ cat /tmp/a
param1=3478374
param2=34128374
param3=34783743

$ 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
share|improve this answer

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

Escaped:

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`]"
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.