Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to derive current date and time and append at the end of each line that contains 'Hello'

Tags:

I have the following file party.txt that contains something like the following:

Hello Jacky
Hello Peter
Bye Johnson
Hello Willy
Bye Johnny
Hello Mary
Hello Wendy

I used the grep hello to capture the contents, but when I use the print date +"%Y-%m-%d' and append to it, I cannot, and I will get many 0 per line.

cat party.txt | grep Hello | awk '{ print date +"%Y-%m-%d"}'

What could I be missing?

like image 429
Jack Avatar asked Sep 11 '12 09:09

Jack


3 Answers

gawk (and recent versions of mawk) have a built-in time/date function, so there is no need to use external tools there.

gawk '/Hello/{print NR " - " $0 " - " strftime("%Y-%m-%d")}' party.txt
like image 106
Alin Avatar answered Nov 09 '22 16:11

Alin


One way using awk:

awk -v date="$(date +"%Y-%m-%d %r")" '/Hello/ { print $0, date}' party.txt

Results:

Hello Jacky 2012-09-11 07:55:51 PM
Hello Peter 2012-09-11 07:55:51 PM
Hello Willy 2012-09-11 07:55:51 PM
Hello Mary 2012-09-11 07:55:51 PM
Hello Wendy 2012-09-11 07:55:51 PM

Note that the date value is only set when awk starts, so it will not change, even if the command takes a long time to run.

like image 32
Steve Avatar answered Nov 09 '22 17:11

Steve


 awk 'BEGIN{"date +'%Y-%m-%d'"|getline d;}/Hello/{print $0,d}' file

will give you:

Hello Jacky  2012-09-11
Hello Peter 2012-09-11
Hello Willy 2012-09-11
Hello Mary 2012-09-11
Hello Wendy 2012-09-11
like image 31
Kent Avatar answered Nov 09 '22 17:11

Kent