How to add a timestamp to each line as it comes out of grep?

I have an endless stream of data coming out of a logger that I associate with grep. I would like to save the grep output to a file, but also include a timestamp at the beginning of each line (the time at which the line appeared). Is there an easy way to do this? Suppose I cannot change the output of the registration process.

+4
source share
1 answer

You can add a static timestamp using sed and date :

 ... | sed "s/^/$(date) /" >> output.txt 

Alternatively, if you need a timestamp , use the gawk strftime function :

 ... | gawk '{ print strftime(), $0 }' 

You can define your favorite formatting:

 ... | gawk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0 }' 

And if buffering is a problem, be sure to clear every line:

 ... | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush() }' 

Alternatively use unbuffer :

 unbuffer ... | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0 }' 

If you don't have gawk , you have a couple of other options :

(a) Install ts (from moreutils ):

 ... | ts '%F %T' 

(b) Use perl :

 ... | perl -pe 's/^/localtime . " "/e' 

or with formatting:

 ... | perl -MPOSIX -pe 's/^/strftime("%Y-%m-%d %H:%M:%S", localtime) . " "/e' 

Do not forget that you can use gmtime instead of localtime if you need to format GMT in your language.

(c) Ask a question .

+5
source

All Articles